Request user and print list

I have a problem printing a list. For example, I have two lists:

a = [1,2,3,4,5]
b = [6,7,8,9,10]

Now I want to ask the user to enter a list name and then print this list.

name = input("Write a list name")

User entered "a"

for x in name:
    print(x)

But this does not work (without printing list "a"). Could you please help me?

ADDITIONAL INFORMATION:

I have a dictionary:

poland = {"poznan": 86470,
          "warszawa": 86484,
          "sopot": 95266}

And lists:

poznan = [1711505, 163780, 932461, 1164703]

warszawa = [1503333, 93311, 93181, 93268, 106958, 106956, 127649, 106801, 107386, 93245, 154078, 107032]

sopot = [228481, 164126, 922891]

And now, if the user writes "poznan", I want to assign the poznan identifier from the dictionary to the variable "city_id", and then print the list with the name "poznan"

+4
source share
2 answers

You need to match the lists with the strings that the user can enter.

Therefore use the dictionary:

lists_dict = {
    'a': [1,2,3,4,5]
    'b': [6,7,8,9,10]
}

key = input("Write a list name")

print lists_dict[key]

:

:

poland = {
    "poznan": {"name": 86470, "lst": [1711505, 163780, 932461, 1164703]},
    "warszawa": {"name": 86484, "lst": [1503333, 93311, 93181, 93268, 106958, 106956, 127649, 106801, 107386, 93245, 154078, 107032]},
    "sopot": {"name": 95266, "lst": [228481, 164126, 922891]}
}

:

key = input("Write a list name")
# print the list under 'lst' for the dictionary under 'key'
# print poland[key]["lst"]
# EDIT: python 3 print a function, thanks @Ffisegydd:
print(poland[key]["lst"])
+11

globals(), print(globals()[name]). input() , .

>>> a = [1,2,3,4,5]
>>> b = [6,7,8,9,10]
>>> name = input("Write a list name ")
Write a list name a
>>> globals()[name]
[1, 2, 3, 4, 5]

OP:

>>> poland = {"poznan": 86470,
...           "warszawa": 86484,
...           "sopot": 95266}
>>> poznan = [1711505, 163780, 932461, 1164703]
>>> warszawa = [1503333, 93311, 93181, 93268, 106958, 106956, 127649, 106801, 107386, 93245, 154078, 107032]
>>> sopot = [228481, 164126, 922891]
>>> name = input("Enter name: ")
Enter name: poznan
>>> city_id = poland[name]
>>> city_id
86470
>>> globals()[name]
[1711505, 163780, 932461, 1164703]
>>> 
+7

Source: https://habr.com/ru/post/1569995/


All Articles