2015-04-13 72 views
0

快速的问题在这里。我有这样的字典(有更多的条目):Python - 在字典里面读字典的值

champlist = { 
     "Aatrox": { 
     "id": 266, 
     "title": "the Darkin Blade", 
     "name": "Aatrox", 
     "key": "Aatrox" 
     }, 
     "Thresh": { 
     "id": 412, 
     "title": "the Chain Warden", 
     "name": "Thresh", 
     "key": "Thresh" 
     } 
} 

而且我喜欢读所有的id。我想这样的

for champ in champlist: 
    print(champ['id']) 

但它说:

print(champ['id']) TypeError: string indices must be integers

它不选择每一个“冠军”是一本字典,但作为一个字符串,任何与此帮助?谢谢!

回答

0

你不能像这样迭代字典。尝试重复的值改为:

for champ in champlist.values(): 
    print(champ['id']) 

为了完整,只是键:

for key in champlist.keys(): 
    print(key) 

,或者如果你需要键值组合:

for key, val in champlist.items(): 
    print('%s - %s', key, val) 

也有相同itervaluesiterkeys,和iteritems返回迭代器而不是列表的方法(更适合大型对象)

+0

我不能给予好评你,但这个工作!谢谢! – Nonitus

+0

没有概率,很确定这已经触及每个新的Python开发者在某个点或另一个点 –

1

试试这个:

Variable = champlist['Thresh']['id'] 

要迭代:使用字典的iterkeys()itervalues(),或iteritems()方法。

看看docs更多信息。 :)

+0

给予好评的答案决斗:P –

0

就试试这个:

print [v['id'] for (k, v) in champlist.iteritems()]