[英]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.