[英]How can I print only the keys of inner dictionaries that are nested within a list, within a dict, in alphabetical order?
[英]How do I print all unique keys among dictionaries within a list?
從 JSON 文件( 縮寫示例 JSON 文件)讀取后,我有一個名為“liveData.plays.allPlays”的列表,其中包含許多具有鍵值對的字典。 字典中的鍵是相似的,但有些有額外的鍵。 我想打印所有唯一鍵,最終目標是在我在 CSV 文件中寫入標題行時將這些鍵用作字段名。 我還需要將相應的值作為 CSV 文件下方的行寫入。
我可以使用以下代碼和整數 0 的操作打印任何單個字典中的所有鍵:
with open('nhlbigtest2.json', 'r') as read_file:
data = json.load(read_file)
for k in data["liveData.plays.allPlays"][0].keys():
print(k)
這產生:
about.dateTime
about.eventId
about.eventIdx
about.goals.away
about.goals.home
about.ordinalNum
about.period
about.periodTime
about.periodTimeRemaining
about.periodType
result.description
result.event
result.eventCode
result.eventTypeId
我可以將整數 0 操作為一個范圍還是此任務需要不同的方法? (使用 Python 3.7)
set
是一種旨在保存唯一值的數據結構。 您可以遍歷字典列表,並使用每個字典的鍵update
一組:
unique_keys = set()
for game_dict in data["liveData.plays.allPlays"]:
unique_keys.update(game_dict.keys())
當您將數據作為 CSV 文件寫入時,我建議使用csv.DictWriter
類。 您可以向它傳遞一系列字段名(例如,一set
鍵,從上面開始,也許重新排序並放入列表中),它會為每個字段寫出列。 如果給定的字典沒有特定的鍵,則其在 CSV 文件中的行將為該列留有空白,但您可以使用restval
參數對其進行自定義(如果您願意,可以輸入'N/A'
或其他內容) .
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.