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

2024-10-03 15:23:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一本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' object has no attribute 'replace'


Tags: the方法字符串livedictionary字典is错误
2条回答
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}

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

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

相关问题 更多 >