python:迭代列表值并获取json中的键

2024-04-27 23:26:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下json:

{
    "repo_url":"git@github.plugin.git",
    "latest_commit":"bfe7bxxxx",
    "old_commit":"a4ccbyyy",
    "region": {
                    "A":["us-south","us-east"],
                    "B":["au-syd","germany"]
            }
 }

如果我提供us-eastus-south作为输入,我需要获得键值A。类似地,如果我提供au-syd或{}作为输入,我需要得到B。如何循环这个json构造。在

我试过以下代码作为起点

^{pr2}$

但这不存在错误

^{3}$

Tags: gitgithubjsonurlrepopluginlatestold
3条回答

我在JavaScript中试过了,希望它能按照您的期望工作。在

var jsonObj = { "repo_url":"git@github.plugin.git", "latest_commit":"bfe7bxxxx", "old_commit":"a4ccbyyy", "region": { "A":["us-south","us-east"], "B":["au-syd","germany"] } }; function input(val) { for (var i in Object.keys(jsonObj.region)) { for (var j in jsonObj.region[Object.keys(jsonObj.region)[i]]) { if (jsonObj.region[Object.keys(jsonObj.region)[i]][j] == val) { console.log(Object.keys(jsonObj.region)[i]); } } } } input("us-east");

和13;
和13;

如评论所述。这就是你想要的。在

For python3.*

for majorkey, subdict in output_json['region'].items():
    print(subdict)

For python2.*

^{pr2}$

您需要使用iteritems,而不是仅仅迭代dict

In [3]: for k, v in output_json['region'].iteritems():
   ...:     if 'us-south' in v:
   ...:         print(v.index('us-south'))
   ...:         print(k)
   ...:         
0
A

相关问题 更多 >