Python: Iterate Through Dictionary And Create List With Results
I would like to iterate through a dictionary in Python in the form of: dictionary = { 'company': { 0: 'apple', 1: 'berry', 2: 'pear' }, 'co
Solution 1:
I suppose your keys are strings as well and the output is a list of lists, where the elements are strings, too. Then this problem can be solved via list comprehension.
The idea is to use list comprehension to fill the list of [company, country]
-lists, but only if the country is 'US'
. key
represents the keys of the inner dictionaries (i.e 0, 1, 2).
dictionary = {'company': {0: 'apple', 1: 'berry', 2: 'pear'}, 'country': {0: 'GB', 1: 'US', 2:'US'}}
y = [[dictionary['company'][key], dictionary['country'][key]] for key in dictionary['country'] if dictionary['country'][key] == 'US']
It returns
[['berry', 'US'], ['pear', 'US']]
Solution 2:
myList = []
list(map(lambda x: myList.append(x) if x[1]=='US'elseNone,
zip(dictionary['company'].values(), dictionary['country'].values())))
Post a Comment for "Python: Iterate Through Dictionary And Create List With Results"