简体   繁体   English

提取 python 中的键值对

[英]Extracting Key value pair in python

I have json like below:我有 json 如下所示:

{
  "values" :[
  {
    "cor": "1234567",
    "num": "123456789"
  },
  {
    "cor": "45676677",
    "num": "1234567890"
  },
  {
    "cor": "67899909",
    "num": "1235467898"
  }
]
}

I need output like below:我需要 output 如下所示:

{ "values" :[ { "cor": "1234567", "num": "123456789" }]}
{ "values" :[ { "cor": "45676677", "num": "1234567890" }]}
{ "values" :[ { "cor": "67899909", "num": "1235467898" }]}

I can able to extract the keys and values separately but not able to create the json in the above json format I need.我可以分别提取键和值,但无法以我需要的上述 json 格式创建 json。 Appreciate if anyone can help.感谢是否有人可以提供帮助。

Few code I have used to extract key value pair:我用来提取键值对的代码很少:

for key in data.keys():
    print(key);
for value in data.values():
    print(value);
for item in data["values"]:
    print(item);

This will create a list of the output that you're looking for这将创建您正在寻找的 output 的列表

result = []
for value in data['values']:
    result.append({'values': [value]})

Output: Output:

[{'values': [{'cor': '1234567', 'num': '123456789'}]}, {'values': [{'cor': '45676677', 'num': '1234567890'}]}, {'values': [{'cor': '67899909', 'num': '1235467898'}]}]

If by "output", you mean printing to the console, there's this code:如果通过“输出”,您的意思是打印到控制台,则有以下代码:

for item in my_json["values"]:
    print ({"values":[item]})

As a list, it would be my_list = [{'values':[value]}) for value in my_json['values']] , but that doesn't match the formatting you give.作为一个列表,它是my_list = [{'values':[value]}) for value in my_json['values']] ,但这与您提供的格式不匹配。

If you want a string, you can do my_string = '/n'.join(str({'values':[value]}) for value in my_json['values'])如果你想要一个字符串,你可以做my_string = '/n'.join(str({'values':[value]}) for value in my_json['values'])

The default in Python is to print quotes as single quotes, so if you really want double quotes you'll have to do some string formatting, such as my_string.replace('\'','"') Python 中的默认设置是将引号打印为单引号,因此如果您真的想要双引号,则必须进行一些字符串格式化,例如my_string.replace('\'','"')

The syntax for the replace is a bit confusing because you have to enclose the string that you're replacing in quote marks, but the quote marks are what you're trying to replace, so you have to do something complicated such as escaping the quote marks or using docstring quote demarcations.替换的语法有点混乱,因为您必须将要替换的字符串括在引号中,但引号是您要替换的内容,因此您必须执行一些复杂的操作,例如 escaping the quote标记或使用 docstring 引号分界。

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

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