Dictionary keys match on list; get key/value pair

后端 未结 6 2231
栀梦
栀梦 2021-02-12 14:55

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

6条回答
  •  闹比i
    闹比i (楼主)
    2021-02-12 15:54

    (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}
    

提交回复
热议问题