sallicap
sallicap

Reputation: 75

How do I add a string to each key of a dictionary?

I have a dictionary where each key is composed of a string eg. ['ba'] and each value is list of numbers eg. [1, 2, 3, 4,].

I would like to loop through each key and if the number is >= 100, I would like to add "D" in front of each number eg. 'D123, and if the number is <100, I would like to add "DI" to the front eg. 'DI45". I've written the following code but it doesn't change the dictionary.

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)

Thank you! :)

Upvotes: 1

Views: 173

Answers (3)

Alex
Alex

Reputation: 1126

Here is most compact one-line way:

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',
 ('D125', 'D126', 'D127', 'D128'): 'pa'}

To make it clear

in a case if i less than or equal 100 the ['DI','D'][i>100] gives you ['DI','D'][False] which interpreted as ['DI','D'][0] and return 'DI'

in a case if i great than 100 the ['DI','D'][i>100] gives you ['DI','D'][True] which interpreted as ['DI','D'][1] and return 'D'

Upvotes: 0

hashinclude72
hashinclude72

Reputation: 885

def dict_change(dicto):
    modified_dict = {}
    for key,value in dicto.items():
        key_tuple = tuple((('D' if no>100 else 'DI')+ str(no) for no in key))
        modified_dict[key_tuple] = value
    return modified_dict


old_dict = {(110, 12, 13, 14, 15, 101): 'ba', (12, 126, -127, 128): 'pa'}
print(dict_change(old_dict))

Output

{('D110', 'DI12', 'DI13', 'DI14', 'DI15', 'D101'): 'ba', ('DI12', 'D126', 'DI-127', 'D128'): 'pa'}

Upvotes: 1

Jan
Jan

Reputation: 43169

Using map and a dict comprehension:

dct = {"a": [100, 200, 300], "b": [-100, 200, 100]}

def changer(number):
    char = "D" if number > 100 else "DI"
    return f"{char}{number}"


new_dct = {key: list(map(changer, values)) for key, values in dct.items()}
print(new_dct)

Output

{'a': ['DI100', 'D200', 'D300'], 'b': ['DI-100', 'D200', 'DI100']}

Upvotes: 1

Related Questions