Python 从字典中获取所有值(包括字典中的字典中的值)
例如,如果有一个类似下面的字典,我需要一个函数Python 从字典中获取所有值(包括字典中的字典中的值),python,python-3.x,dictionary,Python,Python 3.x,Dictionary,例如,如果有一个类似下面的字典,我需要一个函数get\u dict\u values(),以便 dic={1:1,2:2,3:{a:“a”,“b:“b”},4:“4”} 打印(获取dic值) >>>[“1”、“2”、“a”、“b”、“4”] 说明: dic.values() dict_values(['1', '2', {'a': 'a', 'b': 'b'}, '4']) 从这里,我们需要获得内部dict的键或值,这不清楚,但假设需要值,我们需要迭代dic。值和如果它是dict我需要内部d
get\u dict\u values()
,以便
dic={1:1,2:2,3:{a:“a”,“b:“b”},4:“4”}
打印(获取dic值)
>>>[“1”、“2”、“a”、“b”、“4”]
说明:
dic.values()
dict_values(['1', '2', {'a': 'a', 'b': 'b'}, '4'])
从这里,我们需要获得内部dict
的键或值,这不清楚,但假设需要值,我们需要迭代dic。值
和如果它是dict
我需要内部dict
的值,即'a',“b”
否则我只需要列表中的项目,即1,2,4
。
为此,我们可以将列表理解与if&else
结合使用
[`do this` if `foo` else `do that` for item in iterator ] ==> if ,else ,for.
对于我们的if条件
,我使用isinstance()
检查内部dict并获取内部dict
的值。
如果它不是一个dict
,那么就给我拿一个项目
isinstance(object, classinfo)
Return True if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof. If object is not an object of the given type, the function always returns False
b=[list(i.values()) if isinstance(i,dict) else i for i in dic.values()]
['1', '2', ['a', 'b'], '4']
这里我们得到了变量b
内部的嵌套列表。为了打破嵌套列表,我使用了另一种理解
[i for elem in b for i in elem ] == [item for sublist in b for item in sublist]
如果我们倒读的话,很容易理解
def getValues(CASE):
if isinstance(CASE, dict):
for VALUE in CASE.values():
yield from getValues(VALUE)
elif isinstance(CASE, list):
for VALUE in CASE:
yield from getValues(VALUE)
else:
yield CASE
if __name__ == '__main__':
TEST_CASE = {
1: "1",
2: "2",
3: {
"a": "a",
"b": "b"
},
4: "4"
}
print(list(getValues(TEST_CASE)))
def getValues(CASE):
if isinstance(CASE, dict):
for VALUE in CASE.values():
yield from getValues(VALUE)
elif isinstance(CASE, list):
for VALUE in CASE:
yield from getValues(VALUE)
else:
yield CASE
if __name__ == '__main__':
TEST_CASE = {
1: "1",
2: "2",
3: {
"a": "a",
"b": "b"
},
4: "4"
}
print(list(getValues(TEST_CASE)))