I would like to iterate through a dictionary in Python in the form of:
dictionary = {'company': {0: 'apple',1: 'berry',2: 'pear'},'country': {0:'GB',1:'US',2:'US'}
}
To grab for example:
every [company, country]
if country
is "US"
So I get a list in the form:
[["berry", "US"], ["pear", "US"]]
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']]