Inverted dictionary | SoloLearn: Learn to code for FREE!

+7

Inverted dictionary

d = dict() #Crerating the dictionary #Adding items to the dictionary d['job'] = ["Scientist", "Researcher"] d['Field'] = ["Biology", "Chemistry", "Computer science", "Healthsciences"] d['Education'] = ["BSc","MSc","PhD"] d['languages'] = ["French", "English", "Spanish", "Berber", "Arabic", "Turkish","Mandarin", "Japanese"] I have this dictionary and i want to write a function that can invert the dictionary where the function will need to turn each of the list items into separate keys in the inverted dictionary.

8/6/2020 6:26:45 PM

Louai Belfounes

22 Answers

New Answer

+18

invDic = lambda x: {i:j for j in x for i in x[j] } print(invDic(d))

+8

Do you want it like this? #it works for lists too https://code.sololearn.com/cGPKs4c6GcpO/?ref=app

+6

Oma Falk i said already just need 1 more comprehention or for statement. just 2 rowa instead of 1 written previously https://code.sololearn.com/czugfo1P5oj3/?ref=app works perfectly Louai Belfounes ,

+6

di={} for k in d: di = {**di,**dict.fromkeys(d[k], k)} https://code.sololearn.com/cU814mpd8csY/?ref=app

+5

george ... Apply it to the dict in question please. It wont work. also not dict(zip(d.items(),d.values()) Louis answer is perfect .

+3

george every key can become a value but not every value(in this case a list) can become a key. So I doubt there is sth for it. If you remember might, it would be worth to be poste here...very interesting

+3

george 👍that's good

+3

george yeah and finally Louis and you provide the same solution. But he belongs to the Anonymous Pythonistas.

+3

Why don't you use a two dimensional list or equivalent data structure like [(x,m),(f,g)].....I guess that should work 🤔🤔🤔

+2

george wont work here

+2

use dictionary comprehention and items function of sictionary. # just any dictionary dict = { "geo": 1, "maria":2} #main func dict comprehention dict ={value:key for (key,value) in dict.items()} #print result print(dict)

+2

Oma Falk Louai Belfounes also according to question to create function i make changes. Now function takes dictionary and returns inverted dictionary P.S. Relax and solution comes itself )))))

+2

my knowledge in programming is c++ and JS. python just for hobby. lousis provide more beatifull solution than me))

+1

As i remember there is integrated function for inver array dictionary. Please check api of python3

+1

Oma Falk sorry?

+1

in case of list just need 1 more comprehension and it will be ok

+1

Louis Thank you for your answer, but since i'am a beginner, i don't really understand it

+1

Sousou Thank you for your contribution

+1

george can you please explain exactly what happens when you used the update method ?

+1

Louai Belfounes merging of 2 dictionaries