我想向字典中现有的键值对添加一个键, 下面的代码是向字典中的键值对添加键的Pythonic方法吗?
region = 'us-west-2'
A = {'m3.large': -1, 'm3.xlarge': -1}
B = {}
for key, value in A.items():
B[(key,region)] = A.get((key, region), 0) + value
print(B)
输出:
{('m3.large', 'us-west-2'): -1, ('m3.xlarge', 'us-west-2'): -1}
另外,我怎样才能在同一个字典上而不是在新字典上做同样的事情?
打印(A)
输出:
{('m3.large', 'us-west-2'): -1, ('m3.xlarge', 'us-west-2'): -1}
谢谢
最佳答案
B = {}
for key, value in A.items():
B[(key,region)] = A.get((key, region), 0) + value
这可以通过字典理解在一个语句中完成。
B = {(key,region): A.get((key, region), 0) + value for key, value in A.items()}
Also how can I do the same thing but on the same dict and not on a new dict ?
字典键是不可变的,所以你不能真正修改它们本身。您可以添加所有新键并删除旧键,但这不如您现在所做的只是创建一个新字典。
关于python - 将键添加到字典中现有的键值对中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41798142/