【问题标题】:How to print the value of dictionary from the file using python如何使用python从文件中打印字典的值
【发布时间】:2019-07-08 09:50:29
【问题描述】:

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

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

['猫','鼠标']

【问题讨论】:

标签: python file dictionary


【解决方案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']

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

【讨论】:

    【解决方案2】:

    您可以使用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)
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2019-04-18
      • 2011-06-27
      • 2023-03-23
      • 1970-01-01
      • 2018-08-06
      • 2015-12-23
      • 1970-01-01
      • 1970-01-01
      • 2022-12-16
      相关资源
      最近更新 更多