Adding new key to dictionary overwrites all previously stored keys with new keys values

前端 未结 1 1630
情深已故
情深已故 2021-01-24 01:47

I\'m trying to use a for loop to generate random values for item prices, by changing the value of the item prices in a pre-defined dictionary.

The new values of this pr

相关标签:
1条回答
  • 2021-01-24 01:57

    The keys in a dictionary are unique. If a key exists in a dictionary, d[key] = other_value just changes the value for that key, it does NOT create another item.

    >>> d = {'a':1, 'b':'foo'}
    >>> d['b'] = 'six'
    >>> d
    {'b': 'six', 'a': 1}
    >>> d.update([('a','bar')])
    >>> d
    {'b': 'six', 'a': 'bar'}
    >>>
    

    If you have data that you want to place in a dictionary and the data contains keys with multiple values, you could put the values into a list for each key. collections.defaultdict makes this easy.

    >>> a
    [('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', 4), ('f', 5), ('a', 100), ('c', 99), ('d', 98), ('f', 97)]
    >>> import collections
    >>> d = collections.defaultdict(list)
    >>> for key, value in a:
        d[key].append(value)
    
    >>> d
    defaultdict(<class 'list'>, {'b': [1], 'a': [0, 100], 'e': [4], 'f': [5, 97], 'd': [3, 98], 'c': [2, 99]})
    >>> 
    

    For your problem, start with the initial values in a list then add to them.

    import random
    
    d = {'a':[0], 'b':[0], 'c':[0]}
    for _ in xrange(4):
        for key in d:
            d[key].append(random.randint(1, 100))
    
    for item in d.items():
        print item
    
    >>>
    ('a', [0, 92, 45, 52, 32])
    ('c', [0, 51, 85, 72, 4])
    ('b', [0, 47, 7, 74, 59])
    >>>
    

    How to iterate over a dictionary.

    0 讨论(0)
提交回复
热议问题