仅选择字典列表中的特定键值

2024-06-01 09:58:28 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的例子:

dictlist = [{'Name': 'James', 'city': 'paris','type': 'A' }, 
            {'Name': 'James','city': 'Porto','type': 'B'},
            {'Name': 'Christian','city': 'LA','type': 'A'}]

我想筛选特定的键值,例如:

desiredKey = [Name,type]

desiredoutput = [{'Name': 'Lara', 'type': 'A' }, 
            {'Name': 'James', 'type': 'B'},
            {'Name': 'Christian','type': 'A'}]

我试过了,但没用

keys =  dictlist[0].keys()
output= [d for d in dictlist if d.keys in desiredKey]

Tags: nameincitytypekeysla例子键值
1条回答
网友
1楼 · 发布于 2024-06-01 09:58:28

您可以尝试以下方法:

In [1]: dictlist = [{'Name': 'James', 'city': 'paris','type': 'A' },  
   ...:             {'Name': 'James','city': 'Porto','type': 'B'}, 
   ...:             {'Name': 'Christian','city': 'LA','type': 'A'}]                                                                                                                                         

In [2]: keys = ["Name","type"]                                                                                                                                                                              

In [3]: res = []                                                                                                                                                                                            

In [5]: for dict1 in dictlist: 
   ...:     result = dict((k, dict1[k]) for k in keys if k in dict1) 
   ...:     res.append(result) 
   ...:                                                                                                                                                                                                     

In [6]: res                                                                                                                                                                                                 
Out[6]: 
[{'Name': 'James', 'type': 'A'},
 {'Name': 'James', 'type': 'B'},
 {'Name': 'Christian', 'type': 'A'}]

相关问题 更多 >