Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
509 views
in Technique[技术] by (71.8m points)

python - Dict with same keys names

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

The result I was expecting was:

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

But instead it was:

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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!

What you can do instead is:

  1. Just create a list of (name, value) pairs, or

    pairs = zip(names, values) # or list(zip(...)) in Python 3
    
  2. create a dictionary mapping names to lists of values.

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...