开发者

Enigmatic Naming of Lists in Python

I am writing a program in python and I am using a dictionary. I need to create an empty list for each key in the dictionary, and each list needs开发者_C百科 to have the same name as the key. The keys are user entered, which is why I can't just make a list in the conventional way. This was the first thing I tried

a = {"x":1, "y":2, "z"3}
list(a.keys())
a.pop() = []   # This raises an error

I also tried to make the lists when the dictionary was being created, but this did not work either:

a = {}
b = input("INPUT1")
c = input("INPUT2")
a[b] = c
b = []

This created a list with the name "b" rather than whatever the user entered. Please help!!


This really doesn't make much sense. Why do your lists need 'names'? For that matter, what do you mean by 'names'?

Secondly, your code doesn't do anything. a.keys() is already a list. Calling list on it doesn't do anything else. But in any case, whatever the result of that line is, it is immediately thrown away, as you don't store the result anywhere.

pop doesn't work on dictionaries, it works on lists. And what does it mean to set the result of pop to a list? Are you trying to dynamically create a set of local variables with the names of each key in the dictionary? If so, why? Why not simply create another dictionary with the keys of the first, and each value as a new list? That can be done in one command:

b = dict((k, []) for k in b.keys())

(Note that dict.fromkeys() won't work here, as that would cause each element to share the same list.)


Use raw_input instead. input expects a valid Python expression and WILL evaluate whatever the user inputs. So if the user inputs a word, it'll evaluate that word and try to find an object with its name.

EDIT: for further clarification, input("INPUT1") is the equivalent of doing eval(raw_input("INPUT1")), for instance.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜