向字典中添加新键会用新键值覆盖所有先前存储的键 [英] Adding new key to dictionary overwrites all previously stored keys with new keys values

查看:178
本文介绍了向字典中添加新键会用新键值覆盖所有先前存储的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用for循环通过更改预定义词典中商品价格的值来生成商品价格的随机值.

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 pre-defined dictionary are then added to the end of another pre-defined dictionary so a history of prices can be stored.

这是我的代码:

tradable_good_prices= {'iron' : 0, 'gold' : 0, 'lead' : 0, 'ruby' : 0 'emerald' : 0, 'steel' : 0, 'diamond' : 0} 
item_list = tradable_good_prices.keys() 
item_price_history = {}

def Random_economy(generations):

    for generation_number in range(0, generations): 

        for list_number in range(0, len(item_list)): 

            tradable_good_prices[item_list[list_number]] = np.random.random_integers(100,1000) 

        print(tradable_good_prices)

        item_price_history[generation_number] = tradable_good_prices 

        print(item_price_history)

Random_economy(2)

该代码以代数作为for循环迭代次数的参数.并将值2世代使用,将在控制台上生成此输出:

the code takes in generations as an argument for the number of for loop iterations. And using a value of 2 for generations this output is produced on the console:

{'steel': 821, 'diamond': 477, 'lead': 325, 'gold': 914, 'iron': 542, 'emerald': 360, 'ruby': 705}

{0: {'steel': 821, 'diamond': 477, 'lead': 325, 'gold': 914, 'iron': 542, 'emerald': 360, 'ruby': 705}}

{'steel': 751, 'diamond': 158, 'lead': 322, 'gold': 662, 'iron': 180, 'emerald': 846, 'ruby': 570}

{0: {'steel': 751, 'diamond': 158, 'lead': 322, 'gold': 662, 'iron': 180, 'emerald': 846, 'ruby': 570}, 1: {'steel': 751, 'diamond': 158, 'lead': 322, 'gold': 662, 'iron': 180, 'emerald': 846, 'ruby': 570}}

可以看到以前的值被覆盖,我想对此有一个简单的解释,例如存储不同世代值的字典正在为其值引用第一个".随处可见.

As can be seen the previous values are being overwritten, I'm guessing theres quite a simple explanation for this like "the dictionary storing the different generation values is referencing the first one for its values" but I cannot find help on this matter anywhere.

所以有人可以向我解释我在做错什么.

So could someone please explain to me what I'm doing wrong.

推荐答案

字典中的键是唯一的.如果字典中存在某个键,则d[key] = other_value只会更改该键的值,而不会创建其他项.

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'}
>>>

如果您有要放置在字典中的数据,并且该数据包含具有多个值的键,则可以将这些值放入每个键的列表中. collections.defaultdict使这变得容易.

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])
>>>


如何在字典上进行迭代.

这篇关于向字典中添加新键会用新键值覆盖所有先前存储的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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