user3803404
user3803404

Reputation: 3

How extract all values for one set of key

How extract all values from one set of key, without write all keys, for the a dictionary with two (or more) entries, not use loop, for example:

dictionary={'a':{'a1':'1','a2':'2','a3':'3'},'b':{'a1':'x','a2':'y','a3':'z'}}

dictionary[*]['a1']

I will can return '1' & 'x'

Upvotes: 0

Views: 115

Answers (2)

Adeel
Adeel

Reputation: 781

import operator

dictionary={'a':{'a1':'1','a2':'2','a3':'3'},'b':{'a1':'x','a2':'y','a3':'z'}}

map(operator.itemgetter('a1'), dictionary.itervalues())

OUTPUT:
['1', 'x']

In case if you want multiple items

result = map(operator.itemgetter('a1', 'a2'), dictionary.itervalues())
zip(*result)

OUTPUT:
[('1', 'x'), ('2', 'y')]

If you wanted as dictionary

keys = ['a1', 'a2']
values = map(operator.itemgetter(*keys), dictionary.itervalues())
dict(zip(keys, zip(*values)))

OUTPUT:
{'a1': ('1', 'x'), 'a2': ('2', 'y')}

Upvotes: 0

merlin2011
merlin2011

Reputation: 75575

It looks like you are looking for a list comprehension.

dictionary={'a':{'a1':'1','a2':'2','a3':'3'},'b':{'a1':'x','a2':'y','a3':'z'}}

output = [dictionary[x]['a1'] for x in dictionary]
print output

Output:

['1', 'x']

If there is concern that the subkey a1 does not exist for all values, then we should probably switch to dict.get, which will return None for all those cases where a1 is not in the dictionary.

output = [dictionary[x].get('a1') for x in dictionary]

Alternately, if we do not want a filler None value, we can do as JohnClements suggested and use a filter.

output = [dictionary[x]['a1'] for x in dictionary if 'a1' in dictionary[x]]

Upvotes: 3

Related Questions