【发布时间】:2018-02-05 18:27:49
【问题描述】:
我已经坚持了一个小时,不知道会是什么。这一定是个愚蠢的事情。
我有一个文件,其中包含一些账户余额的数据:
currency:CZK amount:10000 available:3000 priceUSD:500
currency:EUR amount:500 available:100 priceUSD:600
currency:GBP amount:1000 available:800 priceUSD:1400
在这里我尝试读取文件——我有一个名为 dp 的字典来存储每一行中的数据。比我想将它添加到一个名为 d 的字典中,并以货币为键。
d, dp = {}, {}
with open('balances.txt', 'r') as f:
for line in f:
pairs = line.split()
currency = pairs.pop(0).split(':')[1]
for p in pairs:
ls = p.split(':')
key = ls[0]
value = ls[1]
dp[key] = value
d[currency] = dp
但不是我想要的输出:
{'CZK': {'amount': '10000', 'available': '3000', 'priceUSD': '500'},
'EUR': {'amount': '500', 'available': '100', 'priceUSD': '600'},
'GBP': {'amount': '1000', 'available': '800', 'priceUSD': '1400'}}
我明白了:
{'CZK': {'amount': '1000', 'available': '800', 'priceUSD': '1400'},
'EUR': {'amount': '1000', 'available': '800', 'priceUSD': '1400'},
'GBP': {'amount': '1000', 'available': '800', 'priceUSD': '1400'}}
如果我运行调试器并观察字典的值,dp 总是会更改 d 中的所有值,而不仅仅是具有相应键的值。
【问题讨论】:
标签: python file dictionary for-loop