Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to switch values and keys with python dict?

My input is:

files = {
    'Input.txt': 'Randy',
    'Code.py': 'Stan',
    'Output.txt': 'Randy'
} 

I want the output as:

{'Randy':['Input.txt','Output.txt'], 'Stan':['Code.py']}

Basicly it's the other direction of this switch key and values in a dict of lists

This is what I tried:

dictresult= {}
for key,value in files.items():
     dictresult[key]=value
     dictresult[value].append(key)

But it doesn't work. I get KeyError: 'Randy'

like image 731
Luis Avatar asked Dec 23 '22 23:12

Luis


2 Answers

Here's simple approach where we iterate over keys and values of your original dict files and create list for each value to append to it all keys corresponding to that value.

files = {
    'Input.txt': 'Randy',
    'Code.py': 'Stan',
    'Output.txt': 'Randy'
}

dictresult= {}

for k, v in files.items():
    if v not in dictresult:
        dictresult[v] = [k]
    else:
        dictresult[v].append(k)

print(dictresult) # -> {'Randy': ['Output.txt', 'Input.txt'], 'Stan': ['Code.py']}
like image 179
Filip Młynarski Avatar answered Dec 28 '22 23:12

Filip Młynarski


There are a few problems with your code.

Let's review:

  • Firstly, you're getting key error because you're trying to append a value to key that doesn't exist. Why? because in you earlier statement you added a value to dict[key] and now you're trying to access/append dict[value].

    dictresult[key]=value
    
  • You're assigning value to newly generated key, without any check. every new value will overwrite it.

    dictresult[value].append(key)
    
  • Then you're trying to append a new value to a string using a wrong key.

You can achieve what you want by the following code:

d = {}
for key,value in files.items():
if value in d:
    d[value].append(key)
else:
    d[value] = [key]
print(d)

It will output:

{'Randy': ['Input.txt', 'Output.txt'], 'Stan': ['Code.py']}

How/why it works?

Let's review:

  • The if condition checks if that key is already present in the dictionary. When iterated over a dictionary, it returns it's keys only, not key value pairs unlike dict.items()
  • If the key is there we simply append the current value to it.
  • In other case, where that key is not present, we add a new key to dictionary but we do it by casting it to a list, otherwise a string would be inserted as a value, not a list and you won't be able to append to it.
like image 28
Nauman Naeem Avatar answered Dec 29 '22 01:12

Nauman Naeem