Prasanna Prasanna - 1 year ago 98
Python Question

Adding multiple key,value pair using dictionary comprehension

for a list of dictionaries

sample_dict = [
{'a': 'woot', 'b': 'nope', 'c': 'duh', 'd': 'rough', 'e': '1'},
{'a': 'coot', 'b': 'nope', 'c': 'ruh', 'd': 'rough', 'e': '2'},
{'a': 'doot', 'b': 'nope', 'c': 'suh', 'd': 'rough', 'e': '3'},
{'a': 'soot', 'b': 'nope', 'c': 'fuh', 'd': 'rough', 'e': '4'},
{'a': 'toot', 'b': 'nope', 'c': 'cuh', 'd': 'rough', 'e': '1'}

How do I make a separate dictionary that contains all the key,value pair that match to a certain key. With list comprehension I created a list of all the key,value pairs like this:

container = [[key,val] for s in sample_dict for key,val in s.iteritems() if key == 'a']

Now the container gave me

[['a', 'woot'], ['a', 'coot'], ['a', 'doot'], ['a', 'soot'], ['a', 'toot']]

Which is all fine... but if I want to do the same with dictionaries, I get only a singe key,value pair. Why does this happen ?

container = {key : val for s in sample_dict for key,val in s.iteritems() if key == 'a'}

The container gives only a single element

{'a': 'toot'}

I want the something like

{'a': ['woot','coot','doot','soot','toot']}

How do I do this with minimal change to the code above ?

Answer Source

You are generating multiple key-value pairs with the same key, and a dictionary will only ever store unique keys.

If you wanted just one key, you'd use a dictionary with a list comprehension:

container = {'a': [s['a'] for s in sample_dict if 'a' in s]}

Note that there is no need to iterate over the nested dictionaries in sample_dict if all you wanted was a specific key; in the above I simply test if the key exists ('a' in s) and extract the value for that key with s['a']. This is much faster than looping over all the keys.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download