2015-10-19 86 views
1

我想从我的字典中只获取“代码”值,但不知道我是否正确。理想的情况是我出认沽应该是唯一的代码只从字典中获取特定值

peq = { 
'sg':{'code':9, 'perror':0}, 
'6e':{'code':17, 'perror':0}, 
'g8':{'code':25, 'perror':0}, 
'i7':{'code':33, 'perror':0}, 
'9h':{'code':41, 'perror':0}, 
'it':{'code':49, 'perror':0}, 
'ic':{'code':57, 'perror':0}, 
'9w':{'code':65, 'perror':0}, 
's2':{'code':73, 'perror':0}, 
'ai':{'code':81, 'perror':0} 
} 



for the_value['code'], in peq.iteritems(): 
    print the_value 
+0

你是什么意思你不知道?它工作与否? – Maroun

+0

'print the_value ['code']''而不是'print the_value' –

回答

4

你应该遍历值在这种情况下:

for value in peq.itervalues(): 
    print value['code'] 

您也可以顺利通过的项目,但返回键/值对的元组,其中值是每一个内部字典实例:

for key, value in peq.iteritems(): 
    print value['code'] 
+0

谢谢@black panda –

0
>>> for key in peq: 
     print peq[key]['code'] 
0

这是一种不同的方法,将返回所有“C颂歌”作为一个列表值:

map(lambda x: x['code'], peq.values()) 

的这个结果将是:

[41, 65, 17, 81, 73, 57, 9, 49, 33, 25] 

很明显,你可以遍历说:

for i in map(lambda x: x['code'], peq.values()): 
    print(i) 
0

试大熊猫,它可以比你更可以想象

In [16]: peq = { 
    ....: 'sg':{'code':9, 'perror':0}, 
    ....: '6e':{'code':17, 'perror':0}, 
    ....: 'g8':{'code':25, 'perror':0}, 
    ....: 'i7':{'code':33, 'perror':0}, 
    ....: '9h':{'code':41, 'perror':0}, 
    ....: 'it':{'code':49, 'perror':0}, 
    ....: 'ic':{'code':57, 'perror':0}, 
    ....: '9w':{'code':65, 'perror':0}, 
    ....: 's2':{'code':73, 'perror':0}, 
    ....: 'ai':{'code':81, 'perror':0} 
    ....: } 

In [17]: import pandas as pd 

In [18]: data = pd.DataFrame.from_dict(peq) 

In [19]: data 
Out[19]: 
     6e 9h 9w ai g8 i7 ic it s2 sg 
code 17 41 65 81 25 33 57 49 73 9 
perror 0 0 0 0 0 0 0 0 0 0 

In [20]: data.iloc[0] 
Out[20]: 
6e 17 
9h 41 
9w 65 
ai 81 
g8 25 
i7 33 
ic 57 
it 49 
s2 73 
sg  9 
Name: code, dtype: int64 

In [21]: 

some intro大熊猫的

  1. [pandas intro 1]
  2. [pandas 10 minutes]
+0

@PeterWood我认为这个问题是作者实际使用案例的一个子子问题。 –