gpt4 book ai didi

python - 如何使用python从文件中打印字典的值

转载 作者:太空宇宙 更新时间:2023-11-04 01:55:25 25 4
gpt4 key购买 nike

我在文件中有一个字典,并打印文件中的名称值

di = {'elk': [{'url_1': 'localhost:8080/api/running',
'url_2': 'localhost:8080/api/',
'name': 'cat',
'method': 'GET'}],
'a': [{'url_1': 'localhost:8080/api/running',
'url_2': 'localhost:8080/api/',
'name': 'mouse',
'method': 'GET'}]}

#读取文件

import os
with open('g.txt','r') as fh:
fh_n = fh.read()

#保存到列表

test = []
for k,v in di.items():
test.append(v[0]['name'])
test

['cat', 'mouse']

最佳答案

import ast

with open('g.txt','r') as fh:
fh_n = fh.read()

#first split string and convert into dictionary
data = ast.literal_eval(fh_n.split("=")[1].strip())

#or
#di = remove from text file
#ast.literal_eval(fh_n)

name = [i[0]['name'] for i in data.values()]
print(name)

O/P:

['cat', 'mouse']

将文本文件数据转换成json文件g.json 文件

[{
"di": {
"elk": [
{
"url_1": "localhost:8080/api/running",
"url_2": "localhost:8080/api/",
"name": "cat",
"method": "GET"
}
],
"a": [
{
"url_1": "localhost:8080/api/running",
"url_2": "localhost:8080/api/",
"name": "mouse",
"method": "GET"
}
]
}
}
]

.py 文件

import json

with open('g.json') as fh:
data = json.load(fh)

name = [i[0]['name'] for i in data[0]['di'].values()]
print(name)

O/P:

['cat', 'mouse']

关于python - 如何使用python从文件中打印字典的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56932348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com