简体   繁体   English

如何在Python中使用索引获取字典中的键名和值

[英]How to get the key name and value in dict using index in Python

I have below json:我有以下json:

{
    "Static Data": {
        "Maximum Target": "UI-A@supervision-report-production-data-data-1-4:statistics-1:maximum_target",
        "Sigma": "UI-A@supervision-report-production-data-data-1-4:statistics-1:sigma2",
        "Variation Coefficient": "UI-A@supervision-report-production-data-data-1-4:statistics-1:cv",
        "Web Width": "UI-A@supervision-report-production-data-data-1-4:statistics-1:fullwidth"
    },

    "Section": "Winder-A1-roll-1-4:section",
    "StartDateTime": "Winder-A1-3:startTimestamp",
    "StopDateTime": "Winder-A1-3:stopTimestamp"

}

below is the code:下面是代码:

json_data = open(configs_path)
data = json.load(json_data)
json_data.close()

index = 2

print(data['Static Data'][index])

Based on index , I want to get the key name and value of the dict.基于index ,我想获取字典的键名和值。 How can I do this.?我怎样才能做到这一点。?

You can convert a dictionary into a list of key / value pairs您可以将字典转换为key / value对列表

kvpairs = list(data.items())

then kvpairs[0][0] will be the first key and kvpairs[0][1] the first value.那么kvpairs[0][0]将是第一个键, kvpairs[0][1]将是第一个值。

This is not normally needed very often because the accessing a dictionary by index is somewhat a strange requirement.这通常不是经常需要的,因为按索引访问字典有点奇怪。

Note that the conversion to list is necessary if you want to access entries by index, as otherwise the object returned from items is only usable for iteration.请注意,如果要按索引访问条目,则必须转换为list ,否则从items返回的对象仅可用于迭代。

If you need instead what is much more common and is iterating over an array then a simple loop using for ... in will do:如果您需要更常见的东西并且在数组上迭代,那么使用for ... in的简单循环将执行以下操作:

for key, value in data.items():
    ...

If you are using an updated version of Python (3.6≤), skip to the second step, otherwise, you will have to follow the first step of loading your JSON in order:如果您使用的是 Python 的更新版本(3.6≤),请跳到第二步,否则,您必须按照第一步加载您的 JSON:

Step 1 - Load in Order (On older Python versions (<3.6)):步骤 1 - 按顺序加载(在较旧的 Python 版本 (<3.6) 上):

To do that, you will have to load your json with an OrderedDict as the key hook:为此,您必须使用OrderedDict作为关键钩子加载 json:

from collections import OrderedDict

with open(configs_path) as fd:
    json_data = json.load(fd, object_pairs_hook=OrderedDict)

Step 2 - Convert the dictionary (Or inner ones) to list:第 2 步 - 将字典(或内部字典)转换为列表:

You will then have to convert your dictionary into list, so you can access it by index, assuming you want to access only the inner dicts with an index, then you should do something like:然后,您必须将字典转换为列表,以便您可以通过索引访问它,假设您只想访问带有索引的内部字典,那么您应该执行以下操作:

for key, value in json_data.items():
    if isinstance(value, dict):
        json_data[key] = list(value.items())

Then you can access it like:然后你可以像这样访问它:

index = 2
print(json_data['Static Data'][index])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM