I have this python dictionary myDict:
{'Age': {0: '39'}, 'DailyRate': {0: '903'}, 'DistanceFromHome': {0: '2'}, 'EnvironmentSatisfaction': {0: '1'}, 'HourlyRate': {0: '41'}, 'JobInvolvement': {0: '4'}, 'JobLevel': {0: '3'}, 'JobSatisfaction': {0: '3'}, 'MonthlyIncome': {0: '7880'}, 'MonthlyRate': {0: '2560'}, 'NumCompaniesWorked': {0: '0'}, 'PercentSalaryHike': {0: '18'}, 'RelationshipSatisfaction': {0: '4'}, 'StandardHours': {0: '80'}, 'TotalWorkingYears': {0: '9'}, 'TrainingTimesLastYear': {0: '3'}, 'YearsAtCompany': {0: '8'}, 'YearsInCurrentRole': {0: '7'}, 'YearsSinceLastPromotion': {0: '0'}, 'YearsWithCurrManager': {0: '7'}, 'MaritalStatus_': {0: '2'}, 'JobRole_': {0: '7'}, 'Gender_': {0: '1'}, 'EducationField_': {0: '1'}, 'Department_': {0: '2'}, 'BusinessTravel_': {0: '2'}, 'OverTime_': {0: '1'}, 'Over18_': {0: '1'}}
As you can see, if i get a one from above sample as below,
{'Age': {0: '39'}}
There is an additional 0 in front of the value 39. And this zero presents in every key-value pair.
How can I get rid of this 0, so it looks like this:
{'Age': '39'}
I tried this method, but it removes the whole key instead of the 0:
map(myDict.pop, ['Age',''])
Can someone please help me?
You can use dictionary comprehension to solve this issue. Try doing:
new_dict = {key: value[0] for key, value in old_dict.items()}
Here, you iterate through each key, value pair in the dictiory and assign the key of the new dictionary to the key of the old dictionary. But the value becomes the 0th key value of the dictionary inside the dictionary.
For an example, the key starts at 'Age', so the first key of the new dictionary is 'Age'. The value however is {0: '39'}[0] which is '39'. So the first element of the dictionary is 'Age': '39'
you can read it by the following code:
dict= {'Age': {0: '39'}, 'DailyRate': {0: '903'}, 'DistanceFromHome': {0: '2'}, 'EnvironmentSatisfaction': {0: '1'}, 'HourlyRate': {0: '41'}, 'JobInvolvement': {0: '4'}, 'JobLevel': {0: '3'}, 'JobSatisfaction': {0: '3'}, 'MonthlyIncome': {0: '7880'}, 'MonthlyRate': {0: '2560'}, 'NumCompaniesWorked': {0: '0'}, 'PercentSalaryHike': {0: '18'}, 'RelationshipSatisfaction': {0: '4'}, 'StandardHours': {0: '80'}, 'TotalWorkingYears': {0: '9'}, 'TrainingTimesLastYear': {0: '3'}, 'YearsAtCompany': {0: '8'}, 'YearsInCurrentRole': {0: '7'}, 'YearsSinceLastPromotion': {0: '0'}, 'YearsWithCurrManager': {0: '7'}, 'MaritalStatus_': {0: '2'}, 'JobRole_': {0: '7'}, 'Gender_': {0: '1'}, 'EducationField_': {0: '1'}, 'Department_': {0: '2'}, 'BusinessTravel_': {0: '2'}, 'OverTime_': {0: '1'}, 'Over18_': {0: '1'}}
print(dict['Age'][0])
to convert just do:
age = dict['Age'][0]
del(dict['Age'])
dict.update({"Age":age})
you will get the following dic as result:
{'DailyRate': {0: '903'}, 'DistanceFromHome': {0: '2'}, 'EnvironmentSatisfaction': {0: '1'}, 'HourlyRate': {0: '41'}, 'JobInvolvement': {0: '4'}, 'JobLevel': {0: '3'}, 'JobSatisfaction': {0: '3'}, 'MonthlyIncome': {0: '7880'}, 'MonthlyRate': {0: '2560'}, 'NumCompaniesWorked': {0: '0'}, 'PercentSalaryHike': {0: '18'}, 'RelationshipSatisfaction': {0: '4'}, 'StandardHours': {0: '80'}, 'TotalWorkingYears': {0: '9'}, 'TrainingTimesLastYear': {0: '3'}, 'YearsAtCompany': {0: '8'}, 'YearsInCurrentRole': {0: '7'}, 'YearsSinceLastPromotion': {0: '0'}, 'YearsWithCurrManager': {0: '7'}, 'MaritalStatus_': {0: '2'}, 'JobRole_': {0: '7'}, 'Gender_': {0: '1'}, 'EducationField_': {0: '1'}, 'Department_': {0: '2'}, 'BusinessTravel_': {0: '2'}, 'OverTime_': {0: '1'}, 'Over18_': {0: '1'}, 'Age': '39'}
Maybe try the following code:
keys = myDict.keys()
valuesWithZero = myDict.values()
valuesNoZero = []
for item in valuesWithZero:
value_iterator = iter(item.values()) #to make dict_values obj iterable
first_value = next(value_iterator) #obtaining first value
valuesNoZero.append(first_value) #adding to new list
newDict = dict(zip(keys, valuesNoZero)) #combining keys arr and values arr
print(newDict)
# should output: {'Age': '39', 'DailyRate': '903', 'DistanceFromHome': '2', 'EnvironmentSatisfaction': '1', 'HourlyRate': '41', 'JobInvolvement': '4', 'JobLevel': '3', 'JobSatisfaction': '3', 'MonthlyIncome': '7880', 'MonthlyRate': '2560', 'NumCompaniesWorked': '0', 'PercentSalaryHike': '18', 'RelationshipSatisfaction': '4', 'StandardHours': '80', 'TotalWorkingYears': '9', 'TrainingTimesLastYear': '3', 'YearsAtCompany': '8', 'YearsInCurrentRole': '7', 'YearsSinceLastPromotion': '0', 'YearsWithCurrManager': '7', 'MaritalStatus_': '2', 'JobRole_': '7', 'Gender_': '1', 'EducationField_': '1', 'Department_': '2', 'BusinessTravel_': '2', 'OverTime_': '1', 'Over18_': '1'}
Same process as the accepted answer but uses some of Python's functional features.
import operator
zero = operator.itemgetter(0)
newdict = dict(zip(myDict,map(zero, myDict.values())))
Related
event = event = {'Records': [{'eventID': '2339bc590c21035b84f8cc602b12c1d2', 'eventName': 'INSERT', 'eventVersion': '1.1', 'eventSource': 'aws:dynamodb', 'awsRegion': 'us-east-1', 'dynamodb': {'ApproximateCreationDateTime': 1595908037.0, 'Keys': {'id': {'S': '9'}}, 'NewImage': {'last_name': {'S': 'Hus'}, 'id': {'S': '9'}, 'age': {'S': '95'}}, 'SequenceNumber': '3100000000035684810908', 'SizeBytes': 23, 'StreamViewType': 'NEW_IMAGE'}, 'eventSourceARN': 'arn:aws:dynamodb:us-east-1:656441365658:table/glossary/stream/2020-07-28T00:26:55.462'}, {'eventID': 'bbd4073256ef3182b3c00f13ead09501', 'eventName': 'MODIFY', 'eventVersion': '1.1', 'eventSource': 'aws:dynamodb', 'awsRegion': 'us-east-1', 'dynamodb': {'ApproximateCreationDateTime': 1595908037.0, 'Keys': {'id': {'S': '2'}}, 'NewImage': {'last_name': {'S': 'JJ'}, 'id': {'S': '2'}, 'age': {'S': '5'}}, 'SequenceNumber': '3200000000035684810954', 'SizeBytes': 21, 'StreamViewType': 'NEW_IMAGE'}, 'eventSourceARN': 'arn:aws:dynamodb:us-east-1:656441365658:table/glossary/stream/2020-07-28T00:26:55.462'}, {'eventID': 'a9c90c0c4a5a4b64d0314c4557e94e28', 'eventName': 'INSERT', 'eventVersion': '1.1', 'eventSource': 'aws:dynamodb', 'awsRegion': 'us-east-1', 'dynamodb': {'ApproximateCreationDateTime': 1595908037.0, 'Keys': {'id': {'S': '10'}}, 'NewImage': {'last_name': {'S': 'Hus'}, 'id': {'S': '10'}, 'age': {'S': '95'}}, 'SequenceNumber': '3300000000035684810956', 'SizeBytes': 25, 'StreamViewType': 'NEW_IMAGE'}, 'eventSourceARN': 'arn:aws:dynamodb:us-east-1:656441365658:table/glossary/stream/2020-07-28T00:26:55.462'}, {'eventID': '288f4a424992e5917af0350b53f754dc', 'eventName': 'MODIFY', 'eventVersion': '1.1', 'eventSource': 'aws:dynamodb', 'awsRegion': 'us-east-1', 'dynamodb': {'ApproximateCreationDateTime': 1595908037.0, 'Keys': {'id': {'S': '1'}}, 'NewImage': {'last_name': {'S': 'V'}, 'id': {'S': '1'}, 'age': {'S': '2'}}, 'SequenceNumber': '3400000000035684810957', 'SizeBytes': 20, 'StreamViewType': 'NEW_IMAGE'}, 'eventSourceARN': 'arn:aws:dynamodb:us-east-1:656441365658:table/glossary/stream/2020-07-28T00:26:55.462'}]}
The above one coming from dynamodb stream. I need to extract the some value from above
Code is below nothing is returning
def deserialize(event):
data = {}
data["M"] = event
return extract_some(data)
def extract_some(event):
for key, value in list(event.items()):
if (key == "NULL"):
return None
if (key == "S" or key == "BOOL"):
return value
for record in event['Records']:
doc = deserialise(record['dynamodb']['NewImage'])
print (doc)
Expected Out
{'last_name': 'Hus', 'id': '9', 'age': '95'}
{'last_name': 'JJ', 'id': '2', 'age': '5'}
{'last_name': 'Hus', 'id': '10', 'age': '95'}
{'last_name': 'V', 'id': '1', 'age': '2'}
try this,
from pprint import pprint
result = []
for r in event['Records']:
tmp = {}
for k, v in r['dynamodb']['NewImage'].items():
if "S" in v.keys() or "BOOL" in v.keys():
tmp[k] = v.get('S', v.get('BOOL', False))
elif 'NULL' in v:
tmp[k] = None
result.append(tmp)
pprint(result)
[{'age': '95', 'id': '9', 'last_name': 'Hus'},
{'age': '5', 'id': '2', 'last_name': 'JJ'},
{'age': '95', 'id': '10', 'last_name': 'Hus'},
{'age': '2', 'id': '1', 'last_name': 'V'}]
I have this signature:
def aggregate_by_player_id(input, playerid, fields):
By 'fields', i mean fields to sum up grouping by 'playerID' within the 'input'.
I call the function like this:
aggregate_by_player_id(input, 'player', ['stat1','stat3'])
Input look like this:
[{'player': '1', 'stat1': '3', 'stat2': '4', 'stat3': '5'},
{'player': '1', 'stat1': '1', 'stat2': '4', 'stat3': '1'},
{'player': '2', 'stat1': '1', 'stat2': '2', 'stat3': '3'},
{'player': '2', 'stat1': '1', 'stat2': '2', 'stat3': '1'},
{'player': '3', 'stat1': '4', 'stat2': '1', 'stat3': '6'}]
My output structure is:
nested_dic = {value_of_playerid1: {'playerid': value_of_playerid1, 'stat1': value_of_stat1, 'stat2': value_of_stat2},
value_of_playerid2: {'playerid': value_of_playerid2, 'stat2': value_of_stat2, 'stat2': value_of_stat2},
value_of_playerid3: {'playerid': value_of_playerid3, 'stat3': value_of_stat3, 'stat3': value_of_stat3}}
Hence the output should look like:
{'1': {'player': '1', 'stat1': 4, 'stat3': 6},
'2': {'player': '2', 'stat1': 2, 'stat3': 4},
'3': {'player': '3', 'stat1': 4, 'stat3': 6}}
We can use itertools.groupby for this to group on playerid and then sum values across the fields.
from itertools import groupby
from operator import itemgetter
def aggregate_by_player_id(input_, playerid, fields):
player = itemgetter(playerid)
output = {}
for k, v in groupby(input_, key=player):
data = list(v)
stats = {playerid: k}
for field in fields:
stats[field] = sum(int(d.get(field, 0)) for d in data)
output[k] = stats
return output
data.sort(key=player) # data must be pre-sorted on grouping key
results = aggregate_by_player_id(data, 'player', ['stat1', 'stat3'])
{'1': {'player': '1', 'stat1': 4, 'stat3': 6},
'2': {'player': '2', 'stat1': 2, 'stat3': 4},
'3': {'player': '3', 'stat1': 4, 'stat3': 6}}
Capturing the result you're after in a single comprehension might be possible, but is likely not very readable. Here's a simple function that does the work:
data = [
{'player': '1', 'stat1': '3', 'stat2': '4', 'stat3': '5'},
{'player': '1', 'stat1': '1', 'stat2': '4', 'stat3': '1'},
{'player': '2', 'stat1': '1', 'stat2': '2', 'stat3': '3'},
{'player': '2', 'stat1': '1', 'stat2': '2', 'stat3': '1'},
{'player': '3', 'stat1': '4', 'stat2': '1', 'stat3': '6'}
]
def aggregate_dicts(ds, id_field, aggr_fields):
result = {}
for d in ds:
identifier = d[id_field]
if identifier not in result:
result[identifier] = {f: 0 for f in aggr_fields}
for f in aggr_fields:
result[identifier][f] += int(d[f])
return result
print(aggregate_dicts(data, 'player', ['stat1', 'stat3']))
Result:
{'1': {'stat1': 4, 'stat3': 6}, '2': {'stat1': 2, 'stat3': 4}, '3': {'stat1': 4, 'stat3': 6}}
If you want to repeat the identifier inside the dict, just add this line to the if block:
result[identifier][id_field] = identifier
I am facing this problem, I want to separate the dataset that has completed and not complete.
So, I want to put flag like 'complete' in the JSON. Example as in output.
This is the data that i have
data=[{'id': 'abc001',
'demo':{'gender':'1',
'job':'6',
'area':'3',
'study':'3'},
'ex_data':{'fam':'small',
'scholar':'2'}},
{'id': 'abc002',
'demo':{'gender':'1',
'edu':'6',
'qual':'3',
'living':'3'},
'ex_data':{'fam':'',
'scholar':''}},
{'id': 'abc003',
'demo':{'gender':'1',
'edu':'6',
'area':'3',
'sal':'3'}
'ex_data':{'fam':'big',
'scholar':NaN}}]
Output
How can I put the flag and also detect NaN and NULL in JSON?
Output=[{'id': 'abc001',
'completed':'yes',
'demo':{'gender':'1',
'job':'6',
'area':'3',
'study':'3'},
'ex_data':{'fam':'small',
'scholar':'2'}},
{'id': 'abc002',
'completed':'no',
'demo':{'gender':'1',
'edu':'6',
'qual':'3',
'living':'3'},
'ex_data':{'fam':'',
'scholar':''}},
{'id': 'abc003',
'completed':'no',
'demo':{'gender':'1',
'edu':'6',
'area':'3',
'sal':'3'}
'ex_data':{'fam':'big',
'scholar':NaN}}]
Something like this should work for you:
data = [
{
'id': 'abc001',
'demo': {
'gender': '1',
'job': '6',
'area': '3',
'study': '3'},
'ex_data': {'fam': 'small',
'scholar': '2'}
},
{
'id': 'abc002',
'demo': {
'gender': '1',
'edu': '6',
'qual': '3',
'living': '3'},
'ex_data': {'fam': '',
'scholar': ''}},
{
'id': 'abc003',
'demo': {
'gender': '1',
'edu': '6',
'area': '3',
'sal': '3'},
'ex_data': {'fam': 'big',
'scholar': None}
}
]
def browse_dict(dico):
empty_values = 0
for key in dico:
if dico[key] is None or dico[key] == "":
empty_values += 1
if isinstance(dico[key], dict):
for k in dico[key]:
if dico[key][k] is None or dico[key][k] == "":
empty_values += 1
if empty_values == 0:
dico["completed"] = "yes"
else:
dico["completed"] = "no"
for d in data:
browse_dict(d)
print(d)
Output :
{'id': 'abc001', 'demo': {'gender': '1', 'job': '6', 'area': '3', 'study': '3'}, 'ex_data': {'fam': 'small', 'scholar': '2'}, 'completed': 'yes'}
{'id': 'abc002', 'demo': {'gender': '1', 'edu': '6', 'qual': '3', 'living': '3'}, 'ex_data': {'fam': '', 'scholar': ''}, 'completed': 'no'}
{'id': 'abc003', 'demo': {'gender': '1', 'edu': '6', 'area': '3', 'sal': '3'}, 'ex_data': {'fam': 'big', 'scholar': None}, 'completed': 'no'}
Note that I changed NaN to None, because here you are most likely showing a python dictionary, not a JSON file since you are using data =
In a dictionary, the NaN value would be changed for None.
If you have to convert your JSON to a dictionary, refer to the JSON module documentation.
Also please check your dictionary syntax. You missed several commas to separate data.
You should try
The Input is
data = [{'demo': {'gender': '1', 'job': '6', 'study': '3', 'area': '3'}, 'id': 'abc001', 'ex_data': {'scholar': '2', 'fam': 'small'}}, {'demo': {'living': '3', 'gender': '1', 'qual': '3', 'edu': '6'}, 'id': 'abc002', 'ex_data': {'scholar': '', 'fam': ''}}, {'demo': {'gender': '1', 'area': '3', 'sal': '3', 'edu': '6'}, 'id': 'abc003', 'ex_data': {'scholar': None, 'fam': 'big'}}]
Also, Nan will not work in Python. So, instead of Nan we have used None.
for item in data:
item["completed"] = 'yes'
for key in item.keys():
if isinstance(item[key],dict):
for inner_key in item[key].keys():
if (not item[key][inner_key]):
item["completed"] = "no"
break
else:
if (not item[key]):
item["completed"] = "no"
break
The Output will be
data = [{'demo': {'gender': '1', 'job': '6', 'study': '3', 'area': '3'}, 'completed': 'yes', 'id': 'abc001', 'ex_data': {'scholar': '2', 'fam': 'small'}}, {'demo': {'living': '3', 'edu': '6', 'qual': '3', 'gender': '1'}, 'completed': 'no', 'id': 'abc002', 'ex_data': {'scholar': '', 'fam': ''}}, {'demo': {'edu': '6', 'gender': '1', 'sal': '3', 'area': '3'}, 'completed': 'no', 'id': 'abc003', 'ex_data': {'scholar': None, 'fam': 'big'}}]
I'm new to python, so I apologise if this is straight forward. Other questions (here and here) have addressed lists of dicts, but I haven't been able to get this to work.
I have a list of dicts for each geographical area:
list_of_dicts = [{'id': 'a', 'population': '20', 'area': '10'},
{'id': 'a', 'population': '20', 'area': '10'}]
I merely want to calculate the population density for each area, by dividing the 'population': 'value', by the 'area': 'value'. This calculation should create a new item.
The results should look like this:
results = [{'id': 'a', 'population': '20', 'area': '10', 'pop_density': 2},
{'id': 'a', 'population': '30', 'area': '5', 'pop_density': 6}]
Alter the dictionaries
You can simply iterate over every dictionary, and associate 'pop_density' with the population density:
for v in list_of_dicts:
v['pop_density'] = float(v['population'])/float(v['area'])
We need to use float(..) to convert a string '20' to the number 20. We can use int(..) if all values are ints. But perhaps it is safer to work with floats.
Copy the dictionaries
In case you want to create a copy of the list_of_dicts, you can use list comprehension:
[dict(v,pop_density=float(v['population'])/float(v['area'])) for v in list_of_dicts]
Generating:
>>> [dict(v,pop_density=float(v['population'])/float(v['area'])) for v in list_of_dicts]
[{'population': '20', 'area': '10', 'pop_density': 2.0, 'id': 'a'}, {'population': '20', 'area': '10', 'pop_density': 2.0, 'id': 'a'}]
Changing original dictionaries
You can simply iterate over your list of dictionaries and the calculations. Make sure to round the result since you want an integer:
>>> list_of_dicts = [{'id': 'a', 'population': '20', 'area': '10'},
{'id': 'a', 'population': '20', 'area': '10'}]
>>>
>>> for d in list_of_dicts:
d['pop_density'] = int(d['population']) // int(d['area']) # round result by using //
>>> list_of_dicts
[{'pop_density': 2, 'population': '20', 'id': 'a', 'area': '10'}, {'pop_density': 2, 'population': '20', 'id': 'a', 'area': '10'}]
>>>
Creating new dictionaries
Python 3
If you want a new list of dictionaries, you can use a list comprehension:
>>> list_of_dicts = [{'id': 'a', 'population': '20', 'area': '10'},
{'id': 'a', 'population': '20', 'area': '10'}]
>>>
>>> [{'pop_densitiy': int(d['population']) // int(d['area']), **d} for d in list_of_dicts]
[{'area': '10', 'population': '20', 'id': 'a', 'pop_densitiy': 2}, {'area': '10', 'population': '20', 'id': 'a', 'pop_densitiy': 2}]
>>>
Python 2
Note the above uses the dictionary unpacking operator that is only available in python 3. If using Python 2, you'll need to use the dict constructor:
>>> list_of_dicts = [{'id': 'a', 'population': '20', 'area': '10'},
{'id': 'a', 'population': '20', 'area': '10'}]
>>> [dict(d, pop_densitiy=int(d['population']) // int(d['area'])) for d in list_of_dicts]
[{'pop_densitiy': 2, 'population': '20', 'id': 'a', 'area': '10'}, {'pop_densitiy': 2, 'population': '20', 'id': 'a', 'area': '10'}]
>>>
Just iterate over the existing indices and add a new one to them:
results = []
for item in list_of_dicts:
item = item.copy() # since we want a new dict - mind you this is a shallow copy
item["pop_density"] = int(item.get("population", 0)) / float(item.get("area", 1))
results.append(item)
list_of_dicts = [{'id': 'a', 'population': '20', 'area': '10'},
{'id': 'a', 'population': '30', 'area': '5'}]
[dict(j) for j in [ list(i.items()) + [ ('pop_density', int(i['population'])/int(i['area'])) ] for i in list_of_dicts ] ]
Output:
[{'area': '10', 'id': 'a', 'pop_density': 2.0, 'population': '20'},
{'area': '5', 'id': 'a', 'pop_density': 6.0, 'population': '30'}]
I have two list of nested dictionaries with the same keys, but different values:
d1 = {
'distilled ': [{'water': '45'}, {'vodka': '9'}, {'vinegar': '7'}, {'beer': '6'}, {'alcohol': '5'}, {'whiskey': '5'}],
'planted': [{'tree': '30'}, {'seed': '28'}, {'flower': '20'}, {'plant': '7'}, {'bomb': '4'}, {'garden': '2'}]
}
and
d2 = {
'distilled ': [{'water': '14'}, {'vinegar': '9'}, {'wine': '8'}, {'alcohol': '8'}, {'liquid': '7'}, {'whiskey': '6'}, {'beer': '5'}],
'planted ': [{'flower': '28'}, {'tree': '18'}, {'seed': '9'}, {'vegetable': '4'}, {'bush': '3'}, {'grass': '3'}, {'garden': '3'}]
}
I want to merge them in a way that preserves the values and merges only the keys in the nested dictionaries. So that the outcome would look like:
{
'distilled ': [('water', '45', '14'), ('vodka', '9'), ('vinegar', '7', '9'), ('beer', '6', '5'), ('alcohol', '5'), ('whiskey', '5'), ('wine', '8')],
'planted': [('tree', '30', '18'), ('seed', '28', '9'), ('flower', '20', '7'), ('plant', '7'), ('bomb', '4'), ('garden', '2', '3')]
}
I tried merging the two using:
d_merged = { k: [ d1[k], d2_to_compare[k] ] for k in d1 }
but the in the outcome only the values of the first dictionary are presented, obviously. Do you have any ideas on how to fix this? Thank you very much in advance.
I am not sure which way to take from here. Would really appreciate any suggestions! Thanks a lot.
dict only has one key-value pair is not a good idea, but anyway, we can work out like this:
d1 = {
'distilled': [{'water': '45'}, {'vodka': '9'}, {'vinegar': '7'}, {'beer': '6'}, {'alcohol': '5'}, {'whiskey': '5'}],
'planted': [{'tree': '30'}, {'seed': '28'}, {'flower': '20'}, {'plant': '7'}, {'bomb': '4'}, {'garden': '2'}]
}
d2 = {
'distilled': [{'water': '14'}, {'vinegar': '9'}, {'wine': '8'}, {'alcohol': '8'}, {'liquid': '7'}, {'whiskey': '6'}, {'beer': '5'}],
'planted': [{'flower': '28'}, {'tree': '18'}, {'seed': '9'}, {'vegetable': '4'}, {'bush': '3'}, {'grass': '3'}, {'garden': '3'}]
}
d3 = {}
for k, v in d1.items():
k1 = dict([d.items()[0] for d in d1[k]])
k2 = dict([d.items()[0] for d in d2[k]])
ret = []
for d in (set(k1.keys()) | set(k2.keys())):
ret.append((d, k1.get(d), k2.get(d)))
d3[k] = ret
print d3