Melina
Melina

Reputation: 303

Exchange a key and one of its values in a dictionary

I have a small example of exchanging a key and one of its values, but I did not make it work:

dict1 = {1: ['BB', 'CC', 'DD'], 2: ['FF', 'HH', 'GG']}
print(dict1)

for key in dict1:
    for value in dict1[key]:
        if value == 'BB':
            temp = key
            key = value            
            value = temp

print(dict1)

Current output:

{1: ['BB', 'CC', 'DD'], 2: ['FF', 'HH', 'GG']}

Desired output:

{BB: [1, 'CC', 'DD'], 2: ['FF', 'HH', 'GG']}

I have used the temp to exchange the value and key, but why does the output does not change (keeps as same as the original dict1)?

Upvotes: 0

Views: 134

Answers (2)

Giorgos Xou
Giorgos Xou

Reputation: 2174

A Solution?

Here some kind of a solution? (not as i would desire it to be but it does the job) :

dict1 = {1: ['BB', 'CC', 'DD'], 2: ['FF', 'HH', 'GG']}

for key in list(dict1):
    for i, value in enumerate(dict1[key]):
        if value == 'BB':
            dict1[value] = dict1.pop(key)
            dict1[value][i] = key

print(dict1)
{2: ['FF', 'HH', 'GG'], 'BB': [1, 'CC', 'DD']}

^^^⚠️ The sequence is changed ⚠️

References:

You can’t use for-in loop to modify a list because the iteration variable, (item in your example), is only holding the value from your list and not directly pointing to that particular list item...

Upvotes: 1

leaf_soba
leaf_soba

Reputation: 2518

a simple homemade solution, create a new result dict is better than change old dict.

code:

dict1 = {1: ['BB', 'CC', 'DD'], 2: ['FF', 'HH', 'GG']}
result = {}
for k,v in dict1.items():
    if "BB" in v:
        v.remove("BB")
        result["BB"] = [k] + v
    else:
        result[k] = v
print(result)

result:

{'BB': [1, 'CC', 'DD'], 2: ['FF', 'HH', 'GG']}

Upvotes: 0

Related Questions