point from a list into a dicitonary variable

。_饼干妹妹 提交于 2019-12-12 16:36:58

问题


Assume you have a list

a = [3,4,1]

I want with this information to point to the dictionary:

b[3][4][1]

Now, what I need is a routine. After I see the value, to read and write a value inside b's position.

I don't like to copy the variable. I want to change variable b's content directly.


回答1:


Assuming b is a nested dictionary, you could do

reduce(dict.get, a, b)

to access b[3][4][1].

For more general object types, use

reduce(operator.getitem, a, b)

Writing the value is a bit more involved:

reduce(dict.get, a[:-1], b)[a[-1]] = new_value

All this assumes you don't now the number of elements in a in advance. If you do, you can go with neves' answer.




回答2:


This would be the basic algorithm:

To get the value of an item:

mylist = [3, 4, 1]
current = mydict
for item in mylist:
    current = current[item]
print(current)

To set the value of an item:

mylist = [3, 4, 1]
newvalue = "foo"

current = mydict
for item in mylist[:-1]:
    current = current[item]
current[mylist[-1]] = newvalue



回答3:


Assuming the list length is fixed and already known

a = [3, 4, 1]
x, y, z = a
print b[x][y][z]

you can put this inside a function



来源:https://stackoverflow.com/questions/11905188/point-from-a-list-into-a-dicitonary-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!