Nimmala
Nimmala

Reputation: 7

filter list of dictionaries based on a particular value of a key in that dictionary

I have a list of dictionaries as follows

dict = {2308:[{'name':'john'},{'age':'24'},{'employed':'yes'}],3452:[{'name':'sam'},{'age':'45'},{'employed':'yes'}],1234:[{'name':'victor'},{'age':'72'},{'employed':'no'}]}

I want to filter out the above dictionary to new dictionary named new_dict whose age >30.

I tried the following. As I new to programming, could not get the logic.

new_dict =[var for var in dict if dict['age']>30]

But I know it is list of dictionaries, so is there any way I can get the new list dictionaries with age >30

Upvotes: 0

Views: 147

Answers (2)

vash_the_stampede
vash_the_stampede

Reputation: 4606

Solution

people = {
    2308:[
        {'name':'john'},{'age':'24'},{'employed':'yes'}
    ],
    3452:[
        {'name':'sam'},{'age':'45'},{'employed':'yes'}
    ],
    1234:[
        {'name':'victor'},{'age':'72'},{'employed':'no'}
    ]
}

people_over_30 = {}

for k, v in people.items():
    for i in range(len(v)):
        if int(v[i].get('age', 0)) > 30:
            people_over_30[k] = [v]


print(people_over_30)

Output

(xenial)vash@localhost:~/python$ python3.7 quote.py 
{3452: [[{'name': 'sam'}, {'age': '45'}, {'employed': 'yes'}]], 1234: [[{'name': 'victor'}, {'age': '72'}, {'employed': 'no'}]]}

Comments

Unless this is your desired structure for this particular code, I would suggest reformatting your dictionary to look like this

people = {
    2308:
        {'name':'john','age':'24','employed':'yes'}
    ,
    3452:
        {'name':'sam','age':'45','employed':'yes'}
    ,
    1234:
        {'name':'victor','age':'72','employed':'no'}

}

And then your work would be much simpler and able to handle with this instead

for k, v in people.items():
    if int(v.get('age', 0)) > 30:
        people_over_30[k] = [v]

Upvotes: 0

blhsing
blhsing

Reputation: 107124

You can use the following dict comprehension (assuming you store the dictionary in variable d rather than dict, which would shadow the built-in dict class):

{k: v for k, v in d.items() if any(int(s.get('age', 0)) > 30 for s in v)}

This returns:

{3452: [{'name': 'sam'}, {'age': '45'}, {'employed': 'yes'}], 1234: [{'name': 'victor'}, {'age': '72'}, {'employed': 'no'}]}

Upvotes: 1

Related Questions