Ric S
Ric S

Reputation: 9247

Create new dictionary if key is substring of a list

I have the following list and dictionary

lst = [
    'A_blue',
    'A_yellow',
    'A_green',
    'A_red',
    'B_blue',
    'B_yellow',
    'B_green',
    'B_red',
    'C_blue',
    'C_yellow',
    'C_green',
    'C_red'
]

dct = {'blue': 0.5, 'yellow': 0.1, 'green': 0.3, 'red': 0.8}

I would like to obtain a new dictionary where the keys are the elements in lst, and the values are the numbers in dct if the key is a substring of the element in lst.
Basically the output would be something like:

{'A_blue': 0.5, 'A_yellow': 0.1, 'A_green': 0.3, 'A_red': 0.8, 'B_blue': 0.5, ...}

I tried several ways, but I obtained only syntax errors and others; e.g.,

[v for k, v in dct.items() if k in e for e in lst]

gave me UnboundLocalError: local variable 'e' referenced before assignment, which I understand.
But I didn't manage to find a solution, even though should not be that difficult.

Upvotes: 0

Views: 195

Answers (3)

Epsi95
Epsi95

Reputation: 9047

you can try dict comprehension

{i: dct[k] for i in lst for k in dct if k in i}
{'A_blue': 0.5,
 'A_yellow': 0.1,
 'A_green': 0.3,
 'A_red': 0.8,
 'B_blue': 0.5,
 'B_yellow': 0.1,
 'B_green': 0.3,
 'B_red': 0.8,
 'C_blue': 0.5,
 'C_yellow': 0.1,
 'C_green': 0.3,
 'C_red': 0.8}

NOTE: A normal loop may be faster since if k in i effectively iterate for k in dct, so it would be better to use break like this

d = {}
for i in lst:
    for k in dct:
        if k in i:
            d[i] = dct[k]
            break
            
print(d)

Upvotes: 1

balderman
balderman

Reputation: 23815

Try the below

lst = [
    'A_blue',
    'A_yellow',
    'A_green',
    'A_red',
    'B_blue',
    'B_yellow',
    'B_green',
    'B_red',
    'C_blue',
    'C_yellow',
    'C_green',
    'C_red'
]

dct = {'blue': 0.5, 'yellow': 0.1, 'green': 0.3, 'red': 0.8}

result = {x: dct[x[2:]] for x in lst}
print(result)

output

{'A_blue': 0.5, 'A_yellow': 0.1, 'A_green': 0.3, 'A_red': 0.8, 'B_blue': 0.5, 'B_yellow': 0.1, 'B_green': 0.3, 'B_red': 0.8, 'C_blue': 0.5, 'C_yellow': 0.1, 'C_green': 0.3, 'C_red': 0.8}

Upvotes: 0

vnk
vnk

Reputation: 1082

This approach iterates through all the keys in dct and checks it against all the values in lst. If it is a substring, a new key is initialized and the value from dct is set.

newdct = {}
for i in dct.keys():
    for j in lst:
        if j.find(i)!=-1:
            newdct[j] = dct[i]

Output

{'A_blue': 0.5, 'B_blue': 0.5, 'C_blue': 0.5, 'A_yellow': 0.1, 'B_yellow': 0.1, 'C_yellow': 0.1, 'A_green': 0.3, 'B_green': 0.3, 'C_green': 0.3, 'A_red': 0.8, 'B_red': 0.8, 'C_red': 0.8}

Upvotes: 0

Related Questions