gpt4 book ai didi

python - 如何通过唯一键值对有序字典列表中的字典进行寻址?

转载 作者:行者123 更新时间:2023-11-30 23:21:55 27 4
gpt4 key购买 nike

(使用Python 2.7)列表,例如:

L = [
{'ID': 1, 'val': ['eggs']},
{'ID': 2, 'val': ['bacon']},
{'ID': 6, 'val': ['sausage']},
{'ID': 9, 'val': ['spam']}
]

这就是我想要的:

def getdict(list, dict_ID):
for rec in list
if rec['ID'] == dict_ID:
return rec

print getdict(L, 6)

但是有没有一种方法可以直接寻址该字典,而无需遍历列表直到找到它?

用例:读取记录文件(有序字典)。具有重复出现的 ID 的记录中的不同键值必须与首次出现该 ID 的记录合并。

ID 号可能出现在其他键值中,因此 if rec['ID'] in list 会产生误报。

在读取记录(并将它们添加到有序字典列表中)时,我维护一组唯一的 ID,并且仅在新读取的 ID 已存在时才调用 getdict。但话又说回来,这仍然是很多迭代,我想知道是否有更好的方法。

最佳答案

The use case: reading a file of records (ordered dicts). Different key values from records with a re-occurring ID must be merged with the record with the first occurrence of that ID.

为此,您需要使用 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]})

如果您想存储其他对象(例如字典),只需将其作为可调用对象传递即可:

>>> 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': []}})

关于python - 如何通过唯一键值对有序字典列表中的字典进行寻址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24752712/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com