0

I have 4 lists:

list1 = ["in", "france", "germany"]
list2 = ["NAMASTE", "VANAKAM"]
list3 = ["fr1", "fr2", "fr3"]
list4 = ["gem1", "gem2", "gem3", "gem4"]

I want the output as:

[{'in': ["NAMASTE", "VANAKAM"], 'france': ["fr1", "fr2", "fr3"], 'germany': ["gem1", "gem2", "gem3", "gem4"]}]

Can't figure out the way to do this.

All that I'm able to try is:

Lang = {}
counter = 1
for i in list1:
    counter += 1
    Lang[i] = f'list{counter}'
a = []
a.append(Lang)
print(a)

But I'm getting:

[{'in': 'list2', 'france': 'list3', 'germany': 'list4'}]

How can I convert string with same variable name to that variable here so that I get the value of that variable?

Or any other ways to achieve the desired output?

4 Answers4

3

The cleanest way to do what you want to do is:

[dict(zip(list1, [list2, list3, list4]))]

The correct way to do it with your code is (although I recommend you use the code above):

lang = {}
for i, e in enumerate(list1):
    lang[e] = eval(f'list{i + 2}')
a = [lang]
print(a)

See : How to get the value of a variable given its name in a string?

Donatien
  • 151
  • 6
2

Instead of

list1 = ["in", "france", "germany"]
list2 = ["NAMASTE", "VANAKAM"]
list3 = ["fr1", "fr2", "fr3"]
list4 = ["gem1", "gem2", "gem3", "gem4"]

consider using a list of lists:

country_keys = ["in", "france", "germany"]
country_values = [
    ["NAMASTE", "VANAKAM"],
    ["fr1", "fr2", "fr3"],
    ["gem1", "gem2", "gem3", "gem4"],
]

now you can use zip

lang = dict(zip(country_keys, country_values))
Dan
  • 45,079
  • 17
  • 88
  • 157
1

If you really want to explicitly "convert string with same variable name to that variable" you can write

Lang[i] = eval(f'list{counter}')

instead of Lang[i] = f'list{counter}

However, using eval is considered a very bad practice. Some greater clean solutions have been posted in other answers. Consider reading these materials:

Why is using 'eval' a bad practice?

https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html

alexey_zotov
  • 371
  • 1
  • 8
1

Try list comprehension:

list1 = ["in", "france", "germany"]
list2 = ["NAMASTE", "VANAKAM"]
list3 = ["fr1", "fr2", "fr3"]
list4 = ["gem1", "gem2", "gem3", "gem4"]


output = {list1[x]:[list2,list3,list4][x] for x in range(len(list1))}
output

{'in': ['NAMASTE', 'VANAKAM'],
 'france': ['fr1', 'fr2', 'fr3'],
 'germany': ['gem1', 'gem2', 'gem3', 'gem4']}
TitoOrt
  • 1,265
  • 1
  • 11
  • 13