python - How to iterate over particular keys in a dict to get values -


i have large list containing many dictionaries. within each dictionary want iterate on 3 particular keys , dump new list. keys same each dict.

for example, i'd grab keys c, d, e dicts in list below, output list2.

list = [{'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6...},         {'a':10, 'b':20, 'c':30, 'd':40, 'e':50, 'f':60...},         {'a':100, 'b':200, 'c':300, 'd':400, 'e':500, 'f':600...},]  list2 = [{'c':3, 'd':4, 'e':5},          {'c':30, 'd':40, 'e':50},          {'c':300, 'd':400, 'e':500}] 

you can use nested dict comprehension:

keys = ('c', 'd', 'e') [{k: d[k] k in keys} d in list] 

if keys may missing, can use dictionary view object (dict.viewkeys() in python 2, dict.keys() in python 3) find intersection include keys present:

keys = {'c', 'd', 'e'} [{k: d[k] k in d.viewkeys() & keys} d in list] 

demo:

>>> list = [{'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6}, ...         {'a':10, 'b':20, 'c':30, 'd':40, 'e':50, 'f':60}, ...         {'a':100, 'b':200, 'c':300, 'd':400, 'e':500, 'f':600}] >>> keys = ('c', 'd', 'e') >>> [{k: d[k] k in keys} d in list] [{'c': 3, 'e': 5, 'd': 4}, {'c': 30, 'e': 50, 'd': 40}, {'c': 300, 'e': 500, 'd': 400}] >>> list = [{'a':1, 'b':2, 'd':4, 'e':5, 'f':6}, ...         {'a':10, 'b':20, 'c':30, 'd':40, 'f':60}, ...         {'a':100, 'b':200, 'e':500, 'f':600}] >>> keys = {'c', 'd', 'e'} >>> [{k: d[k] k in d.viewkeys() & keys} d in list] [{'e': 5, 'd': 4}, {'c': 30, 'd': 40}, {'e': 500}] 

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -