I have a list of dictionaries in python. For example
mylist = [
{'a': 'x', 'b':'y', 'c':'z'},
{'a':'e','b':'f','c':'g'},
{'a':'h','b':'i','c':'j'}
]
how can i map this into
mynewlist = [
{'a':'x'},
{'a','e'},
{'a':'h'}
]
And
mynewlist2 = [
{'a':'x','b':'y'},
{'a','e','b':'f'},
{'a':'h','b':'i'}
]
You can use list comprehension to do this:
mynewlist = [{'a': item['a']} for item in mylist]
Loop over the list and just grab the a
value from the dict. For mynewlist2
, just do the same thing, but with 2 values:
mynewlist2 = [{'a': item['a'], 'b': item['b']} for item in mylist]