我有以下嵌套字典变量dict2
,我只需打印VarCharValue
中的值(我使用的是python 2.7)
我尝试使用
print (" {0[ResultSet][Rows]}".format(dict2))
但无法获取Data
中的值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'}}}
必需输出
CNT
1
答案 0 :(得分:4)
你的字典里面有很多细分(但也有列表),因此你需要将所有字符编入索引,直到找到所需的元素:
print ("{0[ResultSet][Rows][0][Data][0][VarCharValue]}".format(dict2))
print ("{0[ResultSet][Rows][1][Data][0][VarCharValue]}".format(dict2))
打印:
CNT
1
答案 1 :(得分:0)
递归函数将完成这项工作。它可能远非快速但仍适用于大多数情况。您可以向其提供任何结构的字典,传递您想要的密钥的名称,然后瞧。
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_values)
之类的操作。