【问题标题】:Changes all values in dictionary and not just the corresponding one更改字典中的所有值,而不仅仅是相应的值
【发布时间】: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


    【解决方案1】:

    你应该在你的内部for 循环中创建一个新的dp dict,而不是重复使用它。发生的事情是您正在分配对单个“全局”dp 的引用作为d 中的值。显然,你不希望这样。

    您也可以将最后一行更改为:

    d[currency] = dict(dp)
    

    这与为d 中的每个键创建一个新的dict 效果相同

    【讨论】:

    • 哦,是的 - 这是有道理的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2019-10-17
    • 2011-03-18
    • 2021-11-25
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多