简体   繁体   English

是否可以根据键列表在Python中获取字典的有序“切片”?

[英]Is it possible to take an ordered “slice” of a dictionary in Python based on a list of keys?

Suppose I have the following dictionary and list: 假设我有以下字典和列表:

my_dictionary = {1:"hello", 2:"goodbye", 3:"World", "sand":"box"}
my_list = [1,2,3]

Is there a direct (Pythonic) way to get the key-value pairs out of the dictionary for which the keys are elements in the list, in an order defined by the list order? 是否有直接(Pythonic)方法从列表顺序定义的顺序中获取键是列表中元素的字典中的键值对?

The naive approach is simply to iterate over the list and pull out the values in the map one by one, but I wonder if python has the equivalent of list slicing for dictionaries. 天真的方法只是迭代列表并逐个拉出地图中的值,但我想知道python是否具有相似的字典列表切片。

Don't know if pythonic enough but this is working: 不知道pythonic是否足够但这是有效的:

res = [(x, my_dictionary[x]) for x in my_list]

This is a list comprehension , but, if you need to iterate that list only once, you can also turn it into a generator expression, eg : 这是一个列表理解 ,但是,如果您只需要迭代该列表一次,您还可以将其转换为生成器表达式,例如:

for el in ((x, my_dictionary[x]) for x in my_list):
    print el

Of course the previous methods work only if all elements in the list are present in the dictionary; 当然,只有当列表中的所有元素都存在于字典中时,前面的方法才有效。 to account for the key-not-present case you can do this: 为了解释密钥不存在的情况,你可以这样做:

res = [(x, my_dictionary[x]) for x in my_list if x in my_dictionary]
>>> zip(my_list, operator.itemgetter(*my_list)(my_dictionary))
[(1, 'hello'), (2, 'goodbye'), (3, 'World')]

How about this? 这个怎么样? Take every item in my_list and pass it to the dictionary's get method. 获取my_list每个项目并将其传递给字典的get方法。 It also handles exceptions around missing keys by replacing them with None . 它还通过将其替换为None处理丢失密钥的异常。

map(my_dictionary.get, my_list)

If you want tupples zip it - 如果你想要tupples zip -

zip(my_list, map(my_dictionary.get, my_list))

If you want a new dict, pass the tupple to dict. 如果你想要一个新的字典,请将tupple传递给dict。

dict(zip(my_list, map(my_dictionary.get, my_list)))

A straight forward way would be to pick each item from the dictionary and check if the key is present in the list 一种直接的方法是从字典中选择每个项目并检查列表中是否存在该键

>>> [e for e in my_dictionary.items() if e[0] in my_list]
[(1, 'hello'), (2, 'goodbye'), (3, 'World')]

The above search would be linear so you might gain some performance by converting the list to set 上面的搜索将是线性的,因此您可以通过将列表转换为set来获得一些性能

>>> [e for e in my_dictionary.items() if e[0] in set(my_list)]
[(1, 'hello'), (2, 'goodbye'), (3, 'World')]

And finally if you need a dictionary instead of a list of key,value pair tuples you can use dictionary comprehension 最后,如果您需要字典而不是键,值对元组的列表,您可以使用字典理解

>>> dict(e for e in my_dictionary.items() if e[0] in set(my_list))
{1: 'hello', 2: 'goodbye', 3: 'World'}
>>> 

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

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