尝试转换值列表以用于在字典中查找特定键值。
我无法找出一种Python方式来做到这一点。
试图将列表转换为字符串并作为键传递给字典,但由于列表也包含整数值,因此现在可以使用。
l = ['tsGroups', 0, 'testCases', 0, 'parameters', 'GnbControlAddr', 'ip']
d={
"tsGroups": [{"tsId": 19,
"testCases": [{"name": "abcd",
"type": "xyz",
"parameters": {"GnbControlAddr":
{"ip": "192.1.1.1",
"mac": "",
"mtu": 1500,
"phy": "eth2",
}
}
}]
}]
}
print(d["tsGroups"][0]["testCases"][0]["parameters"]["GnbControlAddr"]
["ip"])
需要将输入列表'l'转换为要用作
的格式d["tsGroups"][0]["testCases"][0]["parameters"]["GnbControlAddr"]["ip"]
答案 0 :(得分:2)
In [5]: d={
...: "tsGroups": [{"tsId": 19,"testCases": [{"name": "abcd","type": "xyz",
...: "parameters": {"GnbControlAddr": {
...: "ip": "192.1.1.1",
...: "mac": "",
...: "mtu": 1500,
...: "phy": "eth2",
...: }
...: }}]}]}
In [6]: L = ['tsGroups', 0, 'testCases', 0, 'parameters', 'GnbControlAddr', 'ip']
In [7]: functools.reduce?
Docstring:
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
Type: builtin_function_or_method
In [8]: t = d
In [9]: for e in L: t = t[e]
In [10]: t
Out[10]: '192.1.1.1'
答案 1 :(得分:0)
不能说这是pythonic,但是遍历列表并更新对新数据结构的引用似乎是可行的:
current = d
for key in l:
current = current[key]
print current