更改字典中的所有值,而不仅仅是相应的值

问题描述 投票:0回答:1

我被困在这一小时,不知道它可能是什么。它必须是愚蠢的东西。

我有一个文件,其中包含一些帐户余额的数据:

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个回答
1
投票

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

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

d[currency] = dict(dp)

这对于在dict中为每个键创建一个新的d具有相同的效果

© www.soinside.com 2019 - 2024. All rights reserved.