Home > Software engineering >  How to turn multiple lists to a dictionary?
How to turn multiple lists to a dictionary?

Time:11-08

I started with 3 text files of translations of words in different languages. I created 4 lists from these files: a key list and 3 language value lists. I thought I could use the zip function to transform it to a dictionary, but I can only pass two values through that function.

CodePudding user response:

You can use zip with unpacking (note the star in front of t below) as follows:

keys = ['dog', 'rain']
korean = ['개', '비']
spanish = ['perro', 'lluvia']
latin = ['canis', 'pluvia']

d = {k: t for (k, *t) in zip(keys, korean, spanish, latin)}
print(d) # {'dog': ['개', 'perro', 'canis'], 'rain': ['비', 'lluvia', 'pluvia']}

CodePudding user response:

Since I'm thinking you would probably want to be able to identify which translation belongs to which language...

keys = ["dog", "rain"]
korean = ["개", "비"]
spanish = ["perro", "lluvia"]
latin = ["canis", "pluvia"]

result = {
    k: {
        "korean": korean[index],
        "spanish": spanish[index],
        "latin": latin[index]
    } for index, k in enumerate(keys)
}

That would allow you to then be able to get the translation of a word using syntax such as result["dog"]["korean"].

CodePudding user response:

Similar to j1-lee's answer but using list slices.

names = ['dog', 'rain']
korean = ['개', '비']
spanish = ['perro', 'lluvia']
latin = ['canis', 'pluvia']

print({z[0]: list(z[1:]) for z in zip(names, korean, spanish, latin)})
  • Related