0

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)?

Melina
  • 293
  • 3
  • 11
  • 1
    The desired output doesn't make sense -- you can't have duplicate keys in a dict. `list1` is really a dict. I don't understand the logic here. Please clarify. – ggorlen Jul 05 '21 at 20:39
  • 1
    I recommend [Python visualization](http://pythontutor.com/visualize.html#mode=display) and [Python names](https://nedbatchelder.com/text/names.html) to help you understand. – jarmod Jul 05 '21 at 20:53
  • 1
    I think the question is clear, but it requires some amount of explanation of how Python fundamentally works as an answer. – mkrieger1 Jul 05 '21 at 20:56
  • 1
    A short answer would be: `key` and `value` are new variables here (i.e. they are copies of the original `key` and `value`). – Jānis Š. Jul 05 '21 at 21:40
  • 1
    [5.5. Dictionaries- It is best to think of a dictionary as a set of key: value pairs, with the requirement that the keys are unique (within one dictionary)](https://docs.python.org/3/tutorial/datastructures.html#:~:text=with%20the%20requirement%20that%20the%20keys%20are%20unique%20(within%20one%20dictionary)) – Giorgos Xou Jul 05 '21 at 21:48
  • [```No, each key in a dictionary should be unique. You can’t have two keys with the same value. Attempting to use the same key again will just overwrite the previous value stored. If a key needs to store multiple values, then the value associated with the key should be a list or another dictionary.```](https://discuss.codecademy.com/t/can-a-dictionary-have-two-keys-of-the-same-value/351465) – Giorgos Xou Jul 05 '21 at 21:53
  • @Giorgos Xou thanks Xou, I had made a mistake on this point, I have just updated the desired output. My intention is simply exchange the value of a key and one of its value:) – Melina Jul 06 '21 at 07:45
  • @Jānis Š. Thanks, I think you get the point of the problem. If `key` and `value` are copies of the original `key` and `value`, how can I exchange the ´real key and value´ though? – Melina Jul 06 '21 at 07:51
  • @jarmod thanks, the visualization is very helpful! – Melina Jul 06 '21 at 07:58
  • 1
    C/C++ approach is impossible in your case in Python. You cannot change the key - only add a new one or delete an existing one. To replace an item in the list, you can either create a new list and assign it to a key or use _ctypes (see an example here by martineau (the last answer): https://stackoverflow.com/questions/44205017/how-to-reference-a-dict-object). – Jānis Š. Jul 06 '21 at 10:15

2 Answers2

1

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...

Giorgos Xou
  • 1,461
  • 1
  • 13
  • 32
0

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']}
leaf_yakitori
  • 2,232
  • 1
  • 9
  • 21