Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从字典中获取所有值(包括字典中的字典中的值)_Python_Python 3.x_Dictionary - Fatal编程技术网

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)))