简体   繁体   English

如何通过唯一键值来处理有序序列列表中的字典?

[英]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.

相关问题 如何在字典列表中获取具有最高值的字典 - How to get the dictionary with the highest value in a list of dicts 如何使用通配符键值从字典列表中检索字典 - How to retrieve dicts from a list of dicts using wildcard key value 如何检查字典是否在字典的键和值列表中,字典可以嵌套在字典的列表中? - How to check if dictionary is within a list of dictionaries on both key and value of dict, where dicts can be nested? 如何将 CSV 读入 Python 字典,其中每个键的值都是字典列表? - How can I read a CSV into a Python dictionary, where each key's value is a list of dicts? 如何使用列表项寻址字典键并附加相应的值 - How to use a list item to address a dictionary key and append the respective value 通过字典 B 列表中的唯一键减少字典 A 列表 - Reducing list of dicts A by unique key from list of dicts B 如何从 Python 列表中删除多个(键、值)条目 - 有序字典 - How to remove multiple (key,value) entries from a Python List - Ordered Dictionary 获取按字典键排序的字典元素列表 - Get list of dictionary elements ordered by dictionary key 从复杂的字典中得出唯一且有序的列表 - Deriving a unique and ordered list from a complex dictionary 如何创建一个字典,其中列表的唯一项作为键,唯一项的计数作为值? - How to create a dictionary with the unique items of a list as key and the count of unique items as value?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM