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

时间:2019-07-08 09:50:29

标签: python file dictionary

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

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']

  

2 个答案:

答案 0 :(得分:1)

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']

OR

将文本文件数据转换为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']

答案 1 :(得分:1)

您可以使用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'}]}
import json
file = open('g.json', 'w')
json.dump(di, file)  # Saving di into g.json file
file.close()

file_open = open('g.json', 'r+')
my_di = json.load(file_open)  # Loading the saved g.json file
file_open.close()

print(type(di))
print(di)

希望对您有帮助。