[英]How to address a dictionary in a list of ordered dicts by unique key value?
(Using Python 2.7) The list, for example: (使用Python 2.7)列表,例如:
L = [
{'ID': 1, 'val': ['eggs']},
{'ID': 2, 'val': ['bacon']},
{'ID': 6, 'val': ['sausage']},
{'ID': 9, 'val': ['spam']}
]
This does what I want: 这就是我想要的:
def getdict(list, dict_ID):
for rec in list
if rec['ID'] == dict_ID:
return rec
print getdict(L, 6)
but is there a way to address that dictionary directly, without iterating over the list until you find it? 但有没有办法直接解决该词典,而不会迭代列表直到找到它?
The use case: reading a file of records (ordered dicts). 用例:读取记录文件(有序的dicts)。 Different key values from records with a re-occurring ID must be merged with the record with the first occurrence of that ID. 来自具有重新出现ID的记录的不同键值必须与具有该ID的第一次出现的记录合并。
ID numbers may occur in other key values, so if rec['ID'] in list
would produce false positives. ID号可能出现在其他键值中,因此if rec['ID'] in list
会产生误报。
While reading records (and adding them to the list of ordered dicts), I maintain a set of unique ID's and only call getdict
if a newly read ID is already in there. 在读取记录(并将它们添加到有序dicts列表中)时,我保留了一组唯一ID,并且只有在新读取的ID已经存在时才调用getdict
。 But then still, it's a lot of iterations and I wonder if there isn't a better way. 但是,它仍然是很多迭代,我想知道是否有更好的方法。
The use case: reading a file of records (ordered dicts). 用例:读取记录文件(有序的dicts)。 Different key values from records with a re-occurring ID must be merged with the record with the first occurrence of that ID. 来自具有重新出现ID的记录的不同键值必须与具有该ID的第一次出现的记录合并。
You need to use a defaultdict
for this: 你需要使用defaultdict
:
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d['a'].append(1)
>>> d['a'].append(2)
>>> d['b'].append(3)
>>> d['c'].append(4)
>>> d['b'].append(5)
>>> print(d['a'])
[1, 2]
>>> print(d)
defaultdict(<type 'list'>, {'a': [1, 2], 'c': [4], 'b': [3, 5]})
If you want to store other objects, for example a dictionary, just pass that as the callable: 如果要存储其他对象(例如字典),只需将其作为可调用对象传递:
>>> d = defaultdict(dict)
>>> d['a']['values'] = []
>>> d['b']['values'] = []
>>> d['a']['values'].append('a')
>>> d['a']['values'].append('b')
>>> print(d)
defaultdict(<type 'dict'>, {'a': {'values': ['a', 'b']}, 'b': {'values': []}})
Maybe I'm missing something, but couldn't you use a single dictionary? 也许我错过了什么,但你不能使用一本字典吗?
L = {
1 : 'eggs',
2 : 'bacon',
6 : 'sausage',
9 : 'spam'
}
Then you can do L.get(ID)
. 然后你可以做L.get(ID)
。 This will either return the value (eggs, etc) or None
if the ID isn't in the dict. 如果ID不在dict中,这将返回值(eggs等)或None
。
You seem to be doing an inverse dictionary lookup, that is a lookup by value instead of a key. 您似乎正在执行逆字典查找,即按值而不是键查找。 Inverse dictionary lookup - Python has some pointers on how to do this efficiently. 反向字典查找 - Python有一些关于如何有效地执行此操作的指示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.