如何向字典的每个键添加一个字符串?

我有一本字典,其中每个键都由一个字符串组成,例如。['ba']每个值都是数字列表,例如。[1, 2, 3, 4,].


我想遍历每个键,如果数字 >= 100,我想在每个数字前面添加“D”,例如。'D123,如果数字<100,我想在前面添加“DI”,例如。'DI45'。我写了下面的代码,但它并没有改变字典。


def dict_change(dicto):

    for key,value in dicto.items():

        for numb in value:

            if numb >= 100:

                numb = 'D' + str(numb)

            else:

                numb = 'DI' + str(numb)

    return dicto


new_dict = dict_change(old_dict)

谢谢!:)


DIEA
浏览 114回答 3
3回答

胡子哥哥

使用map和听写理解:dct = {"a": [100, 200, 300], "b": [-100, 200, 100]}def changer(number):&nbsp; &nbsp; char = "D" if number > 100 else "DI"&nbsp; &nbsp; return f"{char}{number}"new_dct = {key: list(map(changer, values)) for key, values in dct.items()}print(new_dct)输出{'a': ['DI100', 'D200', 'D300'], 'b': ['DI-100', 'D200', 'DI100']}

萧十郎

def dict_change(dicto):&nbsp; &nbsp; modified_dict = {}&nbsp; &nbsp; for key,value in dicto.items():&nbsp; &nbsp; &nbsp; &nbsp; key_tuple = tuple((('D' if no>100 else 'DI')+ str(no) for no in key))&nbsp; &nbsp; &nbsp; &nbsp; modified_dict[key_tuple] = value&nbsp; &nbsp; return modified_dictold_dict = {(110, 12, 13, 14, 15, 101): 'ba', (12, 126, -127, 128): 'pa'}print(dict_change(old_dict))输出{('D110', 'DI12', 'DI13', 'DI14', 'DI15', 'D101'): 'ba', ('DI12', 'D126', 'DI-127', 'D128'): 'pa'}

冉冉说

这是最紧凑的单行方式:src = {(11, 12, 13, 14, 15, 16): 'ba', (125, 126, 127, 128): 'pa'}d_out = {tuple(['Di','D'][i>100]+ str(i) for i in k):v for k,v in src.items()}print(d_out)Out[1]:{('Di11', 'Di12', 'Di13', 'Di14', 'Di15', 'Di16'): 'ba',&nbsp;('D125', 'D126', 'D127', 'D128'): 'pa'}说清楚在这种情况下,如果i less than or equal 100给 ['DI','D'][i>100]你['DI','D'][False]解释为['DI','D'][0]并返回'DI'在这种情况下,如果i great than 100给 ['DI','D'][i>100]你['DI','D'][True]解释为['DI','D'][1]并返回'D'
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python