具有相同键名的字典 [英] Dict with same keys names

查看:126
本文介绍了具有相同键名的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个字典,该字典具有两个名称相同但值不同的键.我尝试执行此操作的一种方法是创建一个类,在该类中放置字典的每个键名,以使它们成为不同的对象:

I need a dictionary that has two keys with the same name, but different values. One way I tried to do this is by creating a class where I would put the each key name of my dictionary, so that they would be different objects:

names = ["1", "1"]
values = [[1, 2, 3], [4, 5, 6]]
dict = {}

class Sets(object):
    def __init__(self,name):
        self.name = name

for i in range(len(names)):
    dict[Sets(names[i])] = values[i]

print dict

我期望的结果是:

{"1": [1, 2, 3], "1": [4, 5, 6]}

但实际上是:

{"1": [4, 5, 6]}

因此,我发现字典中的键是唯一的,拥有两个具有相同名称的键是对字典的错误使用.因此,我需要重新考虑我的问题,并使用Python中可用的其他方法.

So I discovered that keys in a dictionary are meant to be unique, having two keys with the same name is a incorrect use of dictionary. So I need to rethink my problem and use other methods avaliable in Python.

推荐答案

字典无法做到.实际上,它与字典后面的整个 idea 背道而驰.

What you are trying to do is not possible with dictionaries. In fact, it is contrary to the whole idea behind dictionaries.

此外,您的Sets类也无济于事,因为它有效地为每个名称提供了一个新的(随机的)哈希码,这使得除了检查 all <之外,很难从字典中检索项目. /em>项,这违背了dict的目的.您不能执行dict.get(Sets(some_name)),因为这将创建一个 new Sets对象,该对象的哈希码与字典中已有的哈希码不同

Also, your Sets class won't help you, as it effectively gives each name a new (sort of random) hash code, making it difficult to retrieve items from the dictionary, other than checking all the items, which defeats the purpose of the dict. You can not do dict.get(Sets(some_name)), as this will create a new Sets object, having a different hash code than the one already in the dictionary!

相反,您可以做的是:

  1. 只需创建一个(name, value)对的列表,或者

pairs = zip(names, values) # or list(zip(...)) in Python 3

  • 创建一个将名称映射到值列表的字典.

  • create a dictionary mapping names to lists of values.

    dictionary = {}
    for n, v in zip(names, values):
        dictionary.setdefault(n, []).append(v)
    

  • 第一种使用元组列表的方法将具有线性查找时间(基本上,您必须检查所有条目),但是第二种方法是将dict映射到列表,与"multi-关键命令",并且应该很好地满足您的目的.要访问每个键的值,请执行以下操作:

    The first approach, using lists of tuples, will have linear lookup time (you basically have to check all the entries), but the second one, a dict mapping to lists, is as close as you can get to "multi-key-dicts" and should serve your purposes well. To access the values per key, do this:

    for key, values in dictionary.iteritems():
        for value in values:
            print key, value
    

    这篇关于具有相同键名的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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