【问题标题】:How to replace existing key in a dictionary in python?如何在python中替换字典中的现有键?
【发布时间】:2021-02-27 17:40:23
【问题描述】:

所以,我有这个代码。
我想替换python字典中索引1处的特定现有键。 有人对此有想法吗?

from collections import OrderedDict
regDict= OrderedDict()
regDict[("glenn")] = 1
regDict[("elena")] = 2
print("dict",regDict)

打印:

dict OrderedDict([('glenn', 1), ('elena', 2)])

目标输出:

dict OrderedDict([('glenn', 1), ('new', 2)])  # replacing key in index 1  

【问题讨论】:

标签: python dictionary ordereddict


【解决方案1】:

您制作字典的方法有点偏离。让我们从两个列表(一个用于键,一个用于值)中创建一个新字典开始:

keys = ['a', 'b', 'c']
vals = [1.0, 2.0, 3.0]

dictionary = {keys[i]:value for i, value in enumerate(vals)}

这给了我们以下信息:

{'a': 1.0, 'b': 2.0, 'c': 3.0}

你也可以到这里获取更多关于制作字典的帮助:Convert two lists into a dictionary

要将“a”键替换为“aa”,我们可以这样做:

new_key = 'aa'
old_key = 'a'

dictionary[new_key] = dictionary.pop(old_key)

给我们:

{'b': 2.0, 'c': 3.0, 'aa': 1.0}

其他制作字典的方法:

dictionary = {k: v for k, v in zip(keys, values)}

dictionary = dict(zip(keys, values))

其中 'keys' 和 'values' 都是列表。

【讨论】:

  • dict(zip(keys,vals))
  • zip() 很棒,我完全同意 - 有时它更容易看到一切的进展。这就是我链接另一篇文章的原因。
  • 如果有非常干净简单的方法,就不要教人复杂的方法
  • 当我发现许多其他事情令人困惑时,我的回答有助于我学习字典。我并不是说以上是最有效的方法(因此我的链接)。已将zip() 添加到答案中。
【解决方案2】:

这对于字典来说是一种非常糟糕的方法,但解决方案如下所示

index = len(regDict)-1
key = list(regDict.keys())[index]
value = regDict[key]
regDict["new"] = value

注意:这仅在您想更改最后插入的密钥时才有效

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-24
    • 2014-01-13
    • 2015-12-13
    • 2020-01-18
    • 2019-03-16
    • 2017-02-23
    • 2019-04-15
    • 1970-01-01
    相关资源
    最近更新 更多