繁体   English   中英

Python:替换字典键中字符串的最佳方法是什么

[英]Python: What is the best method to replace a string in a dictionary key

我有一个这样的python字典:

{('Live', '2017-Jan', '103400000', 'Amount'): 30, 
 ('Live', '2017-Feb', '103400000', 'Amount'): 31, 
 ('Live', '2017-Mar', '103400000', 'Amount'): 32,
 ('Live', '2017-Jan', '103401000', 'Amount'): 34
}

用“Live2”替换字典中所有键的“Live”字符串的最佳方法是什么?

我已经尝试了以下但它抛出一个错误:

# cellset is the dictionary
for x in cellset:
    x.replace('Live','Live1')

AttributeError: 'tuple' 对象没有属性 'replace'

d = {
    ('Live', '2017-Jan', '103400000', 'Amount'): 30, 
    ('Live', '2017-Feb', '103400000', 'Amount'): 31, 
    ('Live', '2017-Mar', '103400000', 'Amount'): 32,
    ('Live', '2017-Jan', '103401000', 'Amount'): 34
}

new_d = {}

for k, v in d.items():
    new_key = tuple('Live1' if el == 'Live' else el for el in k)
    new_d[new_key] = v

print(new_d)

# Output:
# {('Live1', '2017-Jan', '103400000', 'Amount'): 30, ('Live1', '2017-Feb', '103400000', 'Amount'): 31, ('Live1', '2017-Mar', '103400000', 'Amount'): 32, ('Live1', '2017-Jan', '103401000', 'Amount'): 34}

其他人已经向您展示了如何创建一个用“Live1”代替“Live”的新词典。 如果您希望在原始字典中进行这些替换,则可能的解决方案如下所示

for (head, *rest), v in tuple(d.items()):
    if head == "Live":
        d[("Live1", *rest)] = v
        del d[(head, *rest)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM