简体   繁体   English

Python字典转换为json或yaml

[英]Python dictionary converting to json or yaml

I have parsed a string and converted into a dictionary. 我已经解析了一个字符串并将其转换为字典。 however I would like to be able to get more information from my dictionary and I was thinking creating a son file or yaml file would be more useful. 但是我希望能够从字典中获取更多信息,并且我认为创建子文件或yaml文件会更有用。 please feel free to comment on another way of solving this problem. 请随时评论解决此问题的另一种方法。

import re
regex = '(\w+) \[(.*?)\] "(.*?)" (\d+) "(.*?)" "(.*?)"'
sample2= 'this [condo] "number is" 28 "owned by" "james"'
patern = '(?P<host>\S+)\s(?P<tipe>\[\w+\])\s(?P<txt>"(.*?))\s(?P<number>\d+)\s(?P<txt1>"\w+\s\w+")\s(?P<owner>"\w+)'
m =re.match(patern, sample2)
res = m.groupdict()
print res

and I would get: 我会得到:

{'tipe': '[condo]', 'number': '28', 'host': 'this', 'owner': '"james', 'txt': '"number is"', 'txt1': '"owned by"'}

I would like to be able to sort by owner name and write out the type of house and the house number. 我希望能够按房主姓名排序并写出房屋类型和房号。 for example: 例如:

James:{ type:condo, number: 28} 詹姆斯:{type:condo,number:28}

or any other suggestions? 或其他建议?

The question of json vs yaml boils down to what are you doing with the data you are saving? json vs yaml的问题归结为您要保存的数据在做什么? If you are reusing the data in JS or in another python script then you could use JSON. 如果要在JS或其他python脚本中重复使用数据,则可以使用JSON。 If you were using it in something that uses YAML then use YAML. 如果您在使用YAML的产品中使用它,请使用YAML。 But in terms of your question, unless there is a particular end game or use case for your data, it doesn't matter the format, you could even just do a typical TSV/CSV and it'd be the same. 但是就您的问题而言,除非您的数据有特定的最终游戏或用例,否则格式无关紧要,您甚至可以执行典型的TSV / CSV,并且将是相同的。

To answer your question about how to make a dict in to a json. 回答有关如何对json进行字典操作的问题。

From your example once you have the res dictionary made. 从您的示例中创建出res字典。

import json
with open('someFile.json', 'wb') as outfile:
     json.dump(res, outfile)

Your output file someFile.json will be your dictionary res 您的输出文件someFile.json将成为您的字典res

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

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