簡體   English   中英

從 API 提取數據后,如何從字典列表中打印字典?

[英]How do I print out a dictionary from a list of dictionaries after I pulled data from an API?

我已從 API 中提取數據,並成功將其作為字典列表保存到 json 文件中。 但是,現在我想從該詞典列表中打印出每個詞典。

正在做:

for i in my_data_file.json:
    print(i)

不起作用。 事實上,它打印出來如下:

[
{
a
:
some data
}
,
{
b
:
some data
}

我希望它打印如下:

{a: some data}
{b: some data}

所以每個字典都打印在單獨的行上。 我知道這樣的事情可能是因為如果我嘗試執行以下操作:

list_dict = [{'a': 12}, {'b': 34}, {'c': 56}]

for i in list_dict:
    print(i)

它打印出以下內容:

{'a': 12}
{'b': 34}
{'c': 56}

這正是我想要的。 為了用我的 JSON 文件來實現這一點,我從根本上缺少什么嗎?

您可以使用 JSON 漂亮地打印帶有縮進的 JSON。

import json
sample=[{'a': 12}, {'b': 34}, {'c': 56}]
new= {}
for d in sample:
    new.update(d)
print(json.dumps(new,indent=4))

您可以先閱讀 json 和json庫。 像這樣,

import json 

with open("data.json") as file1: 
    data = json.load(file1)
    
    for i in data: 
        print(i)

使用json package 寫入和讀取 JSON 文件

從你的例子:

list_dict = [{'a': 12}, {'b': 34}, {'c': 56}]

# dump the list_dict to list_dict.json file
with open('list_dict.json', 'w') as fp:
    json.dump(list_dict,fp)

# read it back in
with open('list_dict.json','r') as fr:
    list_dict_readin=json.load(fr)


這里的新變量list_dict_readin將與原始變量list_dict相同。

假設您將文件存儲為my_data.json

import json

with open("my_data.json") as json_file:
    json_list = json.load(json_file)

    for dictionary in json_list:
        print(dictionary)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM