如何在python中获取嵌套字典的内部索引

时间:2014-09-14 18:05:46

标签: python dictionary

我有一个像

这样的词典
A = {1:{1:50,2:60,5:90},2:{7:55,10:102},4:{10:100,12:40}}

如何访问字典的内部索引,即键1,2,5或键10和12 我的意思是我想访问这些元素将它们存储在数组的特定位置,但是在使用循环时,由于某些键不存在,所以存在某种错误。(当我尝试使用A [i] [j]时我的嵌套循环)。 如何解决这种不平衡的关键

6 个答案:

答案 0 :(得分:1)

如果要访问特定键的值,可以使用A[outer_key][inner_key]

执行此操作

例如

>>> A[1][1]
50
>>> A[2][10]
102

如果要迭代所有键,可以使用for,如下所示。

>>> A
{1: {1: 50, 2: 60, 5: 90}, 2: {10: 102, 7: 55}, 4: {10: 100, 12: 40}}
>>> for outer_key in A:
...     print 'Outer Key = ',outer_key
...     for inner_key in A[outer_key]:
...             print '%d,%d' % (inner_key,A[outer_key][inner_key])
... 
Outer Key =  1
1,50
2,60
5,90
Outer Key =  2
10,102
7,55
Outer Key =  4
10,100
12,40

答案 1 :(得分:1)

这将迭代结构并将值填充到numpy数组中:

A = {1:{1:50,2:60,5:90},2:{7:55,10:102},4:{10:100,12:40}}
B = numpy.zeros((4, 12))

for i, row in A.items():
    for j, value in row.items():
        B[i-1, j-1] = value

答案 2 :(得分:0)

您应该使用内置的迭代器来完成此任务。

A = {1:{1:50,2:60,5:90},2:{7:55,10:102},4:{10:100,12:40}}

myArray = list()

for innerDict in A.values():
    for value in innerDict.values():
        myArray.append(value)

print (myArray)

答案 3 :(得分:0)

A = {1:{1:50,2:60,5:90},2:{7:55,10:102},4:{10:100,12:40}}

values =[ x for y in A.itervalues() for x in y.itervalues()]
[50, 60, 90, 102, 55, 100, 40]

如果您想要键和值配对:

key_values =[ x for y in A.itervalues() for x in y.items()]
print key_values

[(1, 50), (2, 60), (5, 90), (10, 102), (7, 55), (10, 100), (12, 40)]

答案 4 :(得分:0)

为了获得子组件 (rj是JSON个对象)

items=rj.items()
si = sorted(items, key=operator.itemgetter(0))

for i in si:
    t=-1
    print i[0]
    for k in i[1]:
        t+=1
        print '   ',i[1].keys()[t],':',i[1].get(k)

print len(rj)

答案 5 :(得分:0)

您可以在get上使用dictionary功能,当None中找不到密钥时,该功能会返回dictionary。因此,如果所有公共密钥都保存在某些set中,则可以通过它进行迭代:

A = {1:{1:50,2:60,5:90},2:{7:55,10:102},4:{10:100,12:40}}

# storing all keys in set not to save repeated keys
keys_list = {key for inner_dict in A.values() for key in list(inner_dict)}

# for each outer key
for i in A.keys():
    print(A[i]) # printing each key to check

    for j in keys_list: # looping through inner dictionary
        if A[i].get(j) is not None: # if the key is found then it is not None
            print ('Outer Key: ', i, " Inner Key: ", j, " Value: ",  A[i][j]) # now you can use A[i][j]

    print('--------------------------------------------------')

输出:

{1: 50, 2: 60, 5: 90}
Outer Key:  1  Inner Key:  1  Value:  50
Outer Key:  1  Inner Key:  2  Value:  60
Outer Key:  1  Inner Key:  5  Value:  90
--------------------------------------------------
{10: 102, 7: 55}
Outer Key:  2  Inner Key:  7  Value:  55
Outer Key:  2  Inner Key:  10  Value:  102
--------------------------------------------------
{10: 100, 12: 40}
Outer Key:  4  Inner Key:  10  Value:  100
Outer Key:  4  Inner Key:  12  Value:  40
--------------------------------------------------