更改字典的键

2024-05-13 18:42:18 发布

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

所以我有下面的格言

dict = {'tma_prot_{}.grnh':[r'$T_n-P_h$'], 'tma_prot_{}.groh':[r'$T_o-P_h$'], 'tma_urea_{}.grcn':[r'$T_c-U_n$'],
        'tma_urea_{}.gron':[r'$T_o-U_n$'], 'tma_wat_{}.grco':[r'$T_c-W_o$']}

所以我不想tma_prot_0.grnh,而是想把0改成任何数字,例如:tma_prot_2.grnh

我从sayl1 = [0, 2, 11]得到的这个值

所以当我打电话的时候

dict["tma_prot_11.grnh"] or dict["tma_prot_2.grnh"]

我应该得到tma_prot_0.grnh的值

[r'$T_n-P_h$']

我想要一本通用词典。你知道吗

我的尝试

for i in l1:
    for key in dict.keys():
        dict["key".format(l1[i])] = dict["key"]

Tags: keyinl1fordicttmaprotwat
3条回答

没有直接的方法可以做到这一点。其他答案尝试重命名键或添加新键。你知道吗

我的解决办法似乎更复杂,但很简单。 它创建一个自定义dict,该dict修改它获得的键,而不是字典键。你知道吗

import re
from collections import UserDict

class MyDict(UserDict):
    digit_regex = re.compile(r'(\d+)')

    def __getitem__(self, item):
        new_key = self.digit_regex.sub('0', item)
        return super().__getitem__(new_key)

d = MyDict({'tma_prot_0.grnh': [r'$T_n-P_h$'], 'tma_prot_0.groh': [r'$T_o-P_h$'],
            'tma_urea_0.grcn': [r'$T_c-U_n$'], 'tma_urea_0.gron': [r'$T_o-U_n$'],
            'tma_wat_0.grco': [r'$T_c-W_o$']})

for i in [0, 2, 11]:
    print(d['tma_prot_{}.grnh'.format(i)])

输出

['$T_n-P_h$']
['$T_n-P_h$']
['$T_n-P_h$']

只需使用新的dict存储实例内容:


template_dict = {'tma_prot_{}.grnh':[r'$T_n-P_h$'], 'tma_prot_{}.groh':[r'$T_o-P_h$'], 'tma_urea_{}.grcn':[r'$T_c-U_n$'],
        'tma_urea_{}.gron':[r'$T_o-U_n$'], 'tma_wat_{}.grco':[r'$T_c-W_o$']}

dict = {}
l1 = [0, 2, 11]

for i in l1:
    for key in template_dict:
        dict[key.format(i)] = template_dict[key]

然后您可以使用dict来处理您的需求。你知道吗

你就快到了:

for i in l1:
    for key in list(dict.keys()):
        dict[key.format(i)] = dict[key]

相关问题 更多 >