问题
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