理想情况下,打印结果将是:
- ainner
- binner1
- cinner2
- dinner3
但是,我只能使用
.keys()
打印出键。json_dict = {"key": "value", "key1": [{"binner": "inner_value"}, {"ainner1": "inner_value1"}, {"cinner": "inner_value"}, {"dinner1": "inner_value1"}]}
def pprint(a_dict):
for k in a_dict["key1"]:
print("-", k.keys())
pprint(json_dict)
结果是:
- dict_keys(['binner'])
- dict_keys(['ainner1'])
- dict_keys(['dinner1'])
- dict_keys(['cinner'])
我正在寻找与此类似的功能:
{print("- {}".format(k)) for k in sorted(a_dict)}
适用于非嵌套词典 最佳答案
您可以尝试以下方法:
json_dict = {"key": "value", "key1": [{"binner": "inner_value"}, {"ainner1": "inner_value1"}, {"cinner": "inner_value"}, {"dinner1": "inner_value1"}]}
new_data = sorted([list(i.keys())[0] for i in json_dict["key1"]])
输出:
['ainner1', 'binner', 'cinner', 'dinner1']