python - Dict with same keys names -


i need dictionary has 2 keys same name, different values. 1 way tried creating class put each key name of dictionary, different objects:

names = ["1", "1"] values = [[1, 2, 3], [4, 5, 6]] dict = {}  class sets(object):     def __init__(self,name):         self.name = name  in range(len(names)):     dict[sets(names[i])] = values[i]  print dict 

the result expecting was:

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

but instead was:

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

[edit] discovered keys in dictionary meant unique, having 2 keys same name incorrect use of dictionary. need rethink problem , use other methods avaliable in python.

what trying not possible dictionaries. in fact, contrary whole idea behind dictionaries.

also, sets class won't you, gives each name new (sort of random) hash code, making difficult retrieve items dictionary, other checking all items, defeats purpose of dict. can not dict.get(sets(some_name)), create new sets object, having different hash code 1 in dictionary!

what can instead is:

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

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

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

the first approach, using lists of tuples, have linear lookup time (you have check entries), second one, dict mapping lists, close can "multi-key-dicts" , should serve purposes well. access values per key, this:

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

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -