-3

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'}
]
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • So, `mynewlist` would have the 1st element from the dict and `mynewlist2` would have the first 2 elements from the dict? What about the 3rd/last element, is that just ignored? – gen_Eric May 09 '22 at 21:06
  • 1
    @PranavHosangadi I am actually very new to python and I tried using map() function but couldnt figure it out. This is actually my first question here, sincere apologies for not adding my attempt to the description – mudit sharma May 09 '22 at 21:12
  • @muditsharma I think your question is fine in its current iteration. Consider adding your attempt, even if it didn't produce the results you were after. – JNevill May 09 '22 at 21:17

2 Answers2

1

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]
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
0

Something like the following should do the trick. Note that this just keeps the trunc_size number of nested dictionaries. Not specific to entries a and b. It's unclear which was needed, but both answers currently on this question will yield different results if your keys in your dictionaries change.

def truncate_nested_dicts(list_of_dicts, trunc_size):
    outlist = []
    outdict = {}
    for d in list_of_dicts:
        for k,v in list(d.items())[:trunc_size]:
            outdict[k]=v
        outlist.append(outdict)
        outdict={}
    return outlist

print(truncate_nested_dicts(mylist, 2)) 
>>>[{'a': 'x', 'b': 'y'}, {'a': 'e', 'b': 'f'}, {'a': 'h', 'b': 'i'}]
JNevill
  • 46,980
  • 4
  • 38
  • 63