Home > Net >  Python Get list of dictionaries from nested dictionary where value is greater than
Python Get list of dictionaries from nested dictionary where value is greater than

Time:04-16

I have a problem. I have a nested dictionary like this:

{1: {'amount': 200.0, 'quantity': 0}, 2: {'amount': 200.0, 'quantity': 0}, 3: {'amount': 200.0, 'quantity': 0}, 4: {'amount': 200.0, 'quantity': 0}, 5: {'amount': 200.0, 'quantity': 0}, 6: {'amount': 200.0, 'quantity': 0}, 7: {'amount': 200.0, 'quantity': 0}, 8: {'amount': 200.0, 'quantity': 0}, 9: {'amount': 200.0, 'quantity': 0}, 10: {'amount': 200.0, 'quantity': 0}}

What I need to do is craete an array/list with all the dictionaries with an amount greater than 10. I already had the following:

list(filter(lambda x: x['amount'] >= 10, myDict.values()))

But this results in a list with only the values of the dictionaries, but I want them to contain the key as well.

I got this right now as result:

[{'amount': 200.0, 'quantity': 0}, {'amount': 200.0, 'quantity': 0}, {'amount': 200.0, 'quantity': 0}, {'amount': 200.0, 'quantity': 0}, {'amount': 200.0, 'quantity': 0}, {'amount': 200.0, 'quantity': 0}, {'amount': 200.0, 'quantity': 0}, {'amount': 200.0, 'quantity': 0}, {'amount': 200.0, 'quantity': 0}, {'amount': 200.0, 'quantity': 0}]

But this is what I need:

[{1: {'amount': 200.0, 'quantity': 0}}, {2: {'amount': 200.0, 'quantity': 0}}, etc]

How can I include the keys as well?

CodePudding user response:

IIUC, a list comprehension should work:

out = [{k:v} for k,v in my_data.items() if v['amount']>=10]

or using filter:

out = [*map(dict, zip(filter(lambda x: x[1]['amount']>=10, my_data.items())))]

Output:

[{1: {'amount': 200.0, 'quantity': 0}},
 {2: {'amount': 200.0, 'quantity': 0}},
 {3: {'amount': 200.0, 'quantity': 0}},
 ...
 {9: {'amount': 200.0, 'quantity': 0}},
 {10: {'amount': 200.0, 'quantity': 0}}]

For a dictionary that you could traverse by key, it's even simpler:

out = {k:v for k,v in my_data.items() if v['amount']>=10}

or

out = dict(filter(lambda x: x[1]['amount']>=10, my_data.items()))

where the output:

{1: {'amount': 200.0, 'quantity': 0},
 2: {'amount': 200.0, 'quantity': 0},
 3: {'amount': 200.0, 'quantity': 0},
 ...
 9: {'amount': 200.0, 'quantity': 0},
 10: {'amount': 200.0, 'quantity': 0}}
  • Related