my_dictionary = { #Use {} to enclose your dictionary! dictionaries are key,value pairs. so for this dict 'fruit' is a key and ['d', 'e', 'f'] are values associated with the key 'fruit'
'fruit' : ['d','e','f'], #indentation within a dict doesn't matter as long as each item is separated by a ,
'candy' : ['a','b','c'] ,
'snack' : ['g','h','i']
}
print my_dictionary['fruit'] # how to access a dictionary.
for key in my_dictionary:
print key #how to iterate through a dictionary, each iteration will give you the next key
print my_dictionary[key] #you can access the value of each key like this, it is however suggested to do the following!
for key, value in my_dictionary.iteritems():
print key, value #where key is the key and value is the value associated with key
print my_dictionary.keys() #list of keys for a dict
print my_dictionary.values() #list of values for a dict
您可以像这样使用^{} :
输出:
如果变量恰好在某个局部作用域中,则可以使用^{}
或您可以创建字典并访问:
用字典!
默认情况下,字典是不排序的,这可能会导致一些问题,但是有一些方法可以使用多维数组或orderedDicts来解决这个问题,但是我们将在以后保存它! 我希望这有帮助!
我不明白你到底想通过这样做来达到什么目的,但这可以通过使用
eval
来实现。不过,我不建议使用eval
。如果你能告诉我们你最终想要达到的目标会更好。编辑
看看Sааааааааааааааа。这样会更好。
eval
有安全风险,我不建议使用它。相关问题 更多 >
编程相关推荐