有没有办法在python字典中保留重复的键 [英] Is there a way to preserve duplicate keys in python dictionary

查看:44
本文介绍了有没有办法在python字典中保留重复的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在字典中存储重复的键?

我有一个特定的要求来形成请求和响应对.

从特定节点到另一个特定节点的请求形成相同的密钥.我需要存储这两个.

但是如果我尝试将它们添加到字典中,第一个将被第二个替换.有什么办法吗?

解决方案

假设您想继续使用字典,我可以想到两个简单的选项.

  1. 您可以将键映射到项目列表.collections 模块中的 defaultdict 使这变得容易.

    <预><代码>>>>进口藏品>>>数据 = collections.defaultdict(list)>>>对于 k, v in (('a', 'b'), ('a', 'c'), ('b', 'c')):...数据[k].append(v)...>>>数据defaultdict(, {'a': ['b', 'c'], 'b': ['c']})

  2. 您可以使用其他数据来消除键的歧义.这可以是时间戳、唯一 ID 号或其他内容.这样做的优点是保留键和值之间的一对一关系,缺点是查找更复杂,因为您总是必须指定 id.下面的例子展示了这可能是如何工作的;它是否对您有好处取决于问题域:

    <预><代码>>>>对于 k, v in (('a', 'b'), ('a', 'c'), ('b', 'c')):...我= 0... while (k, i) 在数据中:...我+= 1... 数据[(k, i)] = v...>>>数据{('a', 1): 'c', ('b', 0): 'c', ('a', 0): 'b'}

is there any way to store duplicate keys in a dictionary?

I have a specific requirement to form pairs of requests and responses.

Requests from a particular node to another particular node form same keys. I need to store both those.

But if I tried to add them to dictionary, first one is being replaced by second. Is there any way?

解决方案

I can think of two simple options, assuming you want to keep using a dictionary.

  1. You could map keys to lists of items. A defaultdict from the collections module makes this easy.

    >>> import collections
    >>> data = collections.defaultdict(list)
    >>> for k, v in (('a', 'b'), ('a', 'c'), ('b', 'c')):
    ...     data[k].append(v)
    ... 
    >>> data
    defaultdict(<type 'list'>, {'a': ['b', 'c'], 'b': ['c']})
    

  2. You could use additional data to disambiguate the keys. This could be a timestamp, a unique id number, or something else. This has the advantage of preserving a one-to-one relationship between keys and values, and the disadvantage of making lookup more complex, since you always have to specify an id. The example below shows how this might work; whether it's good for you depends on the problem domain:

    >>> for k, v in (('a', 'b'), ('a', 'c'), ('b', 'c')):
    ...     i = 0
    ...     while (k, i) in data:
    ...         i += 1
    ...     data[(k, i)] = v
    ... 
    >>> data
    {('a', 1): 'c', ('b', 0): 'c', ('a', 0): 'b'}
    

这篇关于有没有办法在python字典中保留重复的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆