繁体   English   中英

Python json /字典问题

[英]Python json/dictionary questions

我最近开始使用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”,有没有办法做到这一点(拿出与该书有关的所有数据,具有给定的作者姓名)?

在每个条目booklist是一个Python字典,简称dict 访问字典中的字段使用方式book[field_name] 在您的情况下, field_name的值为"author"

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

以下是一些遍历数据的方法:

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

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

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/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM