Reputation: 105
I have a list of dictionaries that have as their values some tuples:
dic1 = {
'persuaded ': [[('teacher', '6'), ('group', '5'), ('man', '5'), ('girl', '5')]],
'removed ': [[('apple', '5'), ('makeup', '4'), ('trash', '4'), ('stain', '4')]]
}
What I need to do is to convert the nested tuples into dictionaries, so that I can compare it with other similar lists afterwards using the keys. The ideal outcome would be something like:
dic2 = {
'persuaded ': [{'teacher': '6'}, {'group': '5'}, {'man': '5'}, {'girl': '5'}],
'removed ': [{'apple': '5'}, {'makeup': '4'}, {'trash': '4'}, {'stain': '4'}]
}
I tried:
dic2 = {}
for x, y in dic1_zipped:
d.setdefault(x, []).append(y)
And:
from collections import defaultdict
dic2= defaultdict( list )
for n,v in dic1_zipped:
fq[n].append(v)
But neither goes deep enough in the dictionary. I would really appreciate any suggestions on how to solve this! Thanks!
Upvotes: 1
Views: 844
Reputation: 122066
If you get rid of the unnecessary list wrapping, i.e.
dic1 = {'persuaded ': [('teacher', '6'), ('group', '5'), ('man', '5'), ('girl', '5')], 'removed ': [('apple', '5'), ('makeup', '4'), ('trash', '4'), ('stain', '4')]}
You can do this pretty simply:
dic2 = dict((k1, dict(v1)) for k1, v1 in dic1.items())
This gives
{'persuaded ': {'girl': '5', 'man': '5', 'group': '5', 'teacher': '6'}, 'removed ': {'apple': '5', 'makeup': '4', 'stain': '4', 'trash': '4'}}
Which seems more useful than a list of single-entry dictionaries.
(If you can't get rid of the extra level of lists, just use dict(v1[0])
.)
Upvotes: 2
Reputation: 1122552
The following nested dict and list comprehensions will do it for you:
dic2 = {key: [{k: v} for sublist in value for k, v in sublist] for key, value in dic1.items()}
Demo:
>>> {key: [{k: v} for sublist in value for k, v in sublist] for key, value in dic1.items()}
{'removed ': [{'apple': '5'}, {'makeup': '4'}, {'trash': '4'}, {'stain': '4'}], 'persuaded ': [{'teacher': '6'}, {'group': '5'}, {'man': '5'}, {'girl': '5'}]}
>>> from pprint import pprint
>>> pprint(_)
{'persuaded ': [{'teacher': '6'}, {'group': '5'}, {'man': '5'}, {'girl': '5'}],
'removed ': [{'apple': '5'}, {'makeup': '4'}, {'trash': '4'}, {'stain': '4'}]}
I am actually surprised you didn't want to have one dictionary per value:
dic2 = {key: {k: v for sublist in value for k, v in sublist} for key, value in dic1.items()}
which produces:
>>> {key: {k: v for sublist in value for k, v in sublist} for key, value in dic1.items()}
{'removed ': {'stain': '4', 'trash': '4', 'apple': '5', 'makeup': '4'}, 'persuaded ': {'group': '5', 'teacher': '6', 'man': '5', 'girl': '5'}}
>>> pprint(_)
{'persuaded ': {'girl': '5', 'group': '5', 'man': '5', 'teacher': '6'},
'removed ': {'apple': '5', 'makeup': '4', 'stain': '4', 'trash': '4'}}
Upvotes: 2