Python 如何从深度嵌套字典打印特定值

Python 如何从深度嵌套字典打印特定值,python,python-2.7,dictionary,Python,Python 2.7,Dictionary,我有下面的嵌套字典变量dict2,我只需要打印VarCharValue中的值(我使用的是python 2.7) 我试着用 print (" {0[ResultSet][Rows]}".format(dict2)) 但无法获取数据内部的值 print dict2 {u'ResultSet': {u'Rows': [{u'Data': [{u'VarCharValue': u'CNT'}]}, {u'Data': [{u'VarCharValue': u'1'}]}], u'ResultSet

我有下面的嵌套字典变量
dict2
,我只需要打印
VarCharValue
中的值(我使用的是python 2.7)

我试着用

print (" {0[ResultSet][Rows]}".format(dict2)) 
但无法获取数据内部的值

print dict2

{u'ResultSet': {u'Rows': [{u'Data': [{u'VarCharValue': u'CNT'}]}, {u'Data': [{u'VarCharValue': u'1'}]}], u'ResultSetMetadata': {u'ColumnInfo': [{u'Scale': 0, u'Nullable': u'UNKNOWN', u'TableName': u'', u'Precision': 19, u'CatalogName': u'hive'}]}}, 'ResponseMetadata': {'RetryAttempts': 0, 'HTTPStatusCode': 200,'HTTPHeaders': {'date': 'Fr GMT', 'connection': 'keep-alive'}}}
所需输出

字典中有很多子目录(但也有列表),因此需要对所有子目录进行索引,直到找到所需的元素:

print ("{0[ResultSet][Rows][0][Data][0][VarCharValue]}".format(dict2)) 
print ("{0[ResultSet][Rows][1][Data][0][VarCharValue]}".format(dict2)) 
其中打印:

CNT
1
字典中有很多子目录(但也有列表),因此需要对所有子目录进行索引,直到找到所需的元素:

print ("{0[ResultSet][Rows][0][Data][0][VarCharValue]}".format(dict2)) 
print ("{0[ResultSet][Rows][1][Data][0][VarCharValue]}".format(dict2)) 
其中打印:

CNT
1

递归函数将完成这项工作。它可能远不是很快,但仍然适用于大多数情况。你可以给它输入任何结构的字典,传递一个你想要的键的名字,然后瞧

    dict2 = {u'ResultSet': {u'Rows': [{u'Data': [{u'VarCharValue': u'CNT'}]}, {u'Data': [{u'VarCharValue': u'1'}]}], u'ResultSetMetadata': {u'ColumnInfo': [{u'Scale': 0, u'Nullable': u'UNKNOWN', u'TableName': u'', u'Precision': 19, u'CatalogName': u'hive'}]}}, 'ResponseMetadata': {'RetryAttempts': 0, 'HTTPStatusCode': 200,'HTTPHeaders': {'date': 'Fr GMT', 'connection': 'keep-alive'}}}

    def get_dict_values(from_dict, get_key):
        '''
        Return the values of specified keys from a nested dictionary.
        '''

        # A list to collect resulting values in.
        list_collect = list()

        # For each key in a dict.
        for dict_key in from_dict.keys():
            # If it's value is an instance of dict.
            if isinstance(from_dict[dict_key], dict):
                # Call self recursively.
                get_list = get_dict_values(from_dict[dict_key], get_key)

                # Extend the list_collect with what we've got from recursive call.
                list_collect.extend(get_list)
            # If a value is anything iterable.
            elif isinstance(from_dict[dict_key], (list, set, tuple, frozenset)):
                # Call self for each element.
                for list_elem in from_dict[dict_key]:
                    # Extend the list_collect with what we've got from recursive call.
                    get_list = get_dict_values(list_elem, get_key)
                    list_collect.extend(get_list)
            elif dict_key == get_key:
                list_collect.extend([from_dict[dict_key]])
        return list_collect

    if __name__ == '__main__':
        varchar_values = get_dict_values(dict2, 'VarCharValue')
        print(varchar_values)

它将返回一个列表,例如
['CNT',1']
,因此如果您希望将值作为字符串,只需执行类似于
'\n.的操作即可。join(varchar\u values)

递归函数将完成这项工作。它可能远不是很快,但仍然适用于大多数情况。你可以给它输入任何结构的字典,传递一个你想要的键的名字,然后瞧

    dict2 = {u'ResultSet': {u'Rows': [{u'Data': [{u'VarCharValue': u'CNT'}]}, {u'Data': [{u'VarCharValue': u'1'}]}], u'ResultSetMetadata': {u'ColumnInfo': [{u'Scale': 0, u'Nullable': u'UNKNOWN', u'TableName': u'', u'Precision': 19, u'CatalogName': u'hive'}]}}, 'ResponseMetadata': {'RetryAttempts': 0, 'HTTPStatusCode': 200,'HTTPHeaders': {'date': 'Fr GMT', 'connection': 'keep-alive'}}}

    def get_dict_values(from_dict, get_key):
        '''
        Return the values of specified keys from a nested dictionary.
        '''

        # A list to collect resulting values in.
        list_collect = list()

        # For each key in a dict.
        for dict_key in from_dict.keys():
            # If it's value is an instance of dict.
            if isinstance(from_dict[dict_key], dict):
                # Call self recursively.
                get_list = get_dict_values(from_dict[dict_key], get_key)

                # Extend the list_collect with what we've got from recursive call.
                list_collect.extend(get_list)
            # If a value is anything iterable.
            elif isinstance(from_dict[dict_key], (list, set, tuple, frozenset)):
                # Call self for each element.
                for list_elem in from_dict[dict_key]:
                    # Extend the list_collect with what we've got from recursive call.
                    get_list = get_dict_values(list_elem, get_key)
                    list_collect.extend(get_list)
            elif dict_key == get_key:
                list_collect.extend([from_dict[dict_key]])
        return list_collect

    if __name__ == '__main__':
        varchar_values = get_dict_values(dict2, 'VarCharValue')
        print(varchar_values)

它将返回一个列表,例如
['CNT',1']
,因此如果您希望将值作为字符串,只需执行类似于
'\n.的操作即可。join(varchar\u values)

太棒了。我从来都不知道格式支持这种操作。太棒了。我从来不知道格式支持这种操作。谢谢你的输入。谢谢你的输入。