python json dict iterate {key: value} 是一样的
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28923518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python json dict iterate {key: value} are the same
提问by callingconvention
i have a json file I am reading in; looks similar to:
我有一个正在阅读的 json 文件;看起来类似于:
[
{
"Destination_IP": "8.8.4.4",
"ID": 0,
"Packet": 105277
},
{
"Destination_IP": "9.9.4.4",
"ID": 0,
"Packet": 105278
}
]
when i parse the json via:
当我通过以下方式解析 json 时:
for json_dict in data:
for key,value in json_dict.iteritems():
print("key: {0} | value: {0}".format(key, value))
I am getting:
我正进入(状态:
key: Destination_IP | value: Destination_IP
I have tried using .items()
and I have tried just iterating over the keys via iterkeys()
and keys()
to no avail.
我已经尝试使用.items()
,我已经通过尝试过遍历键iterkeys()
和keys()
无济于事。
I can call it direct via json_dict['Destination_IP']
and the value returns.
我可以直接通过调用它,json_dict['Destination_IP']
然后返回值。
for json_dict in data:
if 'Destination_IP' in json_dict.keys():
print json_dict['Destination_IP']
returns:
返回:
key: Destination_IP | value: 8.8.4.4
I'm on python 2.7, so any help in running down the value portion would be greatly appreciated.
我在 python 2.7 上,所以任何帮助减少价值部分将不胜感激。
采纳答案by M.javid
Change your string formats index:
更改您的字符串格式索引:
for json_dict in data:
for key,value in json_dict.iteritems():
print("key: {0} | value: {1}".format(key, value))
Or without using index:
或者不使用索引:
for json_dict in data:
for key,value in json_dict.iteritems():
print("key: {} | value: {}".format(key, value))
Also you can using names instead of index:
您也可以使用名称而不是索引:
for json_dict in data:
for key,value in json_dict.iteritems():
print("key: {key} | value: {value}".format(key=key, value=value))
Update: In python3.6 and later, f-string feature added that allow programmers to make formatted string easiest, a f-string work same as template engine that starting by f
prefix and string body come after, and variables and other dynamic things must determine between {}
signs, same as below:
更新:在python3.6及更高版本中,增加了f-string功能,允许程序员最简单地格式化字符串,f-string的工作方式与模板引擎相同,以f
前缀和字符串主体开始,变量和其他动态事物必须确定{}
标志之间,下同:
print(f'key: A | value: {json_dict["A"]}')
>>> key: A | value: X
回答by ozgur
You don't need to specify an index at all:
您根本不需要指定索引:
for key, value in json_dict.iteritems():
print("key: {} | value: {}".format(key, value))