Creating a list from a complex dictionary
3 answers
Assuming each value in the dictionary is a list of pairs, this should do it for you:
[pair[1] for pairlist in dict1.values() for pair in pairlist]
As you can see:
-
dict1.values()
only gets the values ββin your dict, -
for pairlist in dict1.values()
gets all lists of pairs, -
for pair in pairlist
gets all pairs in each of these lists, - and
pair[1]
gets the second value in each pair.
Try it. The Python shell is your friend! ...
>>> dict1 = {}
>>> dict1['a'] = [[1,2], [3,4]]
>>> dict1['b'] = [[5, 6], [42, 69], [220, 284]]
>>>
>>> dict1.values()
[[[1, 2], [3, 4]], [[5, 6], [42, 69], [220, 284]]]
>>>
>>> [pairlist for pairlist in dict1.values()]
[[[1, 2], [3, 4]], [[5, 6], [42, 69], [220, 284]]]
>>> # No real difference here, but we can refer to each list now.
>>>
>>> [pair for pairlist in dict1.values() for pair in pairlist]
[[1, 2], [3, 4], [5, 6], [42, 69], [220, 284]]
>>>
>>> # Finally...
>>> [pair[1] for pairlist in dict1.values() for pair in pairlist]
[2, 4, 6, 69, 284]
While I'm at it, I'll just say: ipython loves you!
+2
source to share
Given the list:
>>> lst = [ [1,2], [3,4] ]
You can extract the second element of each sublist by simply understanding the list:
>>> [x[1] for x in lst]
[2, 4]
If you want to do this for every value in the dictionary, you can iterate over the dictionary. I'm not sure what you want your final data to look like, but something like this might help:
>>> dict1 = {}
>>> dict1['a'] = [ [1,2], [3,4] ]
>>> [(k, [x[1] for x in v]) for k, v in dict1.items()]
[('a', [2, 4])]
dict.items()
returns (key, value) pairs from a dictionary as a list. So this code will extract every key in your dictionary and link it to the list generated as above.
+8
source to share