Dictionary keys match on list; get key/value pair

拜拜、爱过 提交于 2020-08-01 09:36:10

问题


In python... I have a list of elements 'my_list', and a dictionary 'my_dict' where some keys match in 'my_list'.

I would like to search the dictionary and retrieve key/value pairs for the keys matching the 'my_list' elements.

I tried this...

    if any(x in my_dict for x in my_list):
          print set(my_list)&set(my_dict)

But it doesn't do the job.


回答1:


(I renamed list to my_list and dict to my_dict to avoid the conflict with the type names.)

For better performance, you should iterate over the list and check for membership in the dictionary:

for k in my_list:
    if k in my_dict:
        print k, my_dict[k]

If you want to create a new dictionary from these key-value pairs, use

new_dict = {k: my_dict[k] for k in my_list if k in my_dict}



回答2:


Don't use dict and list as variable names. They shadow the built-in functions. Assuming list l and dictionary d:

kv = [(k, d[k]) for k in l if k in d]



回答3:


 new_dict = dict((k, v) for k, v in dict.iteritems() if k in list)

Turning list into a set set(list) may yield a noticeable speed increase




回答4:


What about print([kv for kv in dict.items() if kv[0] in list])




回答5:


Try This:

mydict = {'one': 1, 'two': 2, 'three': 3}
mykeys = ['three', 'one','ten']
newList={k:mydict[k] for k in mykeys if k in mydict}
print newList
{'three': 3, 'one': 1}



回答6:


Here is a one line solution for that

{i:my_dict[i] for i in set(my_dict.keys()).intersection(set(my_list))}


来源:https://stackoverflow.com/questions/6505008/dictionary-keys-match-on-list-get-key-value-pair

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!