Python json/字典问题

2024-06-26 05:57:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近开始用python阅读和编写json,并将一些书籍从提供的json文件实现到库系统中,如下所示

[
  {
    "author": "Chinua Achebe",
    "country": "Nigeria",
    "imageLink": "images/things-fall-apart.jpg",
    "language": "English",
    "link": "https://en.wikipedia.org/wiki/Things_Fall_Apart\n",
    "pages": 209,
    "title": "Things Fall Apart",
    "year": 1958
  },

我做了一小段代码,把我的书放到一个python字典中,然后把它实现到我更大的系统中

import json

with open('C:/Users/daann/Downloads/booksset1.json') as json_file:

    booklist = json.load(json_file)

print(booklist)

我的问题是关于字典以及如何在字典中读取json中的数据,我现在有一个长字典中的数据,但是如何读取,例如仅读取作者?或者只有名字?我完全忘了,到处都找不到

另一个问题,如果我想拿出,比如我放在这里的第一本书,作者叫“Chinua Achebe”,有没有办法(拿出所有关于这本书的资料,并注明作者姓名)


Tags: 文件数据json字典系统作者fileauthor
3条回答

booklist中的每个条目都是Python字典,缩写为dict。访问字典中的字段时使用符号book[field_name]。在您的例子中,field_name具有值"author"

for book in booklist:
    print(book["author"]) # or any field you want

如果要按作者获取书籍,则需要构建另一个查找作者->;书籍:

import collections
books_by_author = collections.defaultdict(list)
for b in booklist:
    books_by_author[d['author']].append(b)

# and then
books_by_Chinua_Achebe = books_by_author['Chinua Achebe']

此链接可能有助于从词典开始:https://realpython.com/python-dicts/

以下是一些迭代数据的方法:

booklist = [
  {
    "author": "Chinua Achebe",
    "country": "Nigeria",
    "imageLink": "images/things-fall-apart.jpg",
    "language": "English",
    "link": "https://en.wikipedia.org/wiki/Things_Fall_Apart\n",
    "pages": 209,
    "title": "Things Fall Apart",
    "year": 1958
  },

   {
    "author": "Joe Jackson",
    "country": "USA",
    "imageLink": "images/white_socks.jpg",
    "language": "English",
    "link": "https://en.wikipedia.org/wiki/white_sox",
    "pages": 500,
    "title": "My Shoes Hurt My Feet",
    "year": 1919
  },

    {
    "author": "Jane Mae",
    "country": "Canada",
    "imageLink": "images/ehhhh.jpg",
    "language": "French",
    "link": "https://en.wikipedia.org/wiki/ehhhh\n",
    "pages": 123,
    "title": "What's That Aboot",
    "year": 2000
  }]


# Get all authors in a list (might want to convert to set to remove duplicates)     
authors = [d["author"] for d in booklist] 
print (authors) 

# Find all books by author 'Chinua Achebe'
for book in booklist:
    if book['author'] == 'Chinua Achebe':
        print (book)


# Find all books later than year 1950         
for book in booklist:
    if book['year'] > 1950:
        print (book['title'], book['year'])

相关问题 更多 >