简体   繁体   English

根据该字典中某个键的特定值过滤字典列表

[英]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. 我想将上述字典过滤掉,并将其命名为年龄大于30的新字典new_dict。

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 但是我知道这是字典列表,所以有什么办法可以获取年龄> 30岁的新列表字典

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): 您可以使用以下dict理解(假设将字典存储在变量d而不是dict ,这将使内置dict类成为阴影):

{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'}]}

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM