1 year ago
#361469

Casey Cushing
optimizing nested dictionary comprehension
I have a dictionary comprehension that works, however I'm not sure if it is very readable/understandable (since I don't understand it well, but i'm a noob).
Data structures:
dict1 = {'this key 1':['this is a comment','this too','finally this'],
'this key 2':['this is a comment2','this too2','finally this2'],
'this key 3':['this is a comment3','this too3','finally this3']}
list1 = ['BlIb','vILB','vliH']
Desired output:
{'BlIb':{'this key 1':['this is a comment','this too','finally this']},
'vILB':{'this key 2':['this is a comment2','this too2','finally this2']},
'vliH':{'this key 3':['this is a comment3','this too3','finally this3']}}
Dictionary comprehensions:
As I said above, this one works, but I'm not sure how readable it is, or if I completely understand the inner dict comprehension (using 'key' twice)
all_data = {idx:{key:dict1[key]} for idx,key in zip(list1,dict1)}
Would this be the best way to do it? and if so could you explain this part{key:Dict[key]}?
And if not, how would you do it?
I've also tried the below, but just adds all three of the Dict items for each List item
all_data = {idx: {key:value for (key,value) in dict1.items()} for idx in list1}
python-3.x
dictionary-comprehension
0 Answers
Your Answer