[英]Count unique values in a JSON
我有一個名為 thefile.json 的 json,它看起來像這樣:
{
"domain": "Something",
"domain": "Thingie",
"name": "Another",
"description": "Thing"
}
我正在嘗試編寫一個 python 腳本,它將在域中創建一組值。 在這個例子中,它將返回
{'Something', 'Thingie'}
這是我嘗試過的:
import json
with open("thefile.json") as my_file:
data = json.load(my_file)
ids = set(item["domain"] for item in data.values())
print(ids)
我收到錯誤消息
unique_ids.add(item["domain"])
TypeError: string indices must be integers
在堆棧交換上查找答案后,我很難過。 為什么我不能將字符串作為索引,因為我正在使用數據類型為字典的 json(我認為!)? 我如何獲得它以便我可以獲得“域”的值?
因此,首先,您可以在此處閱讀有關 JSON 格式的更多信息: https : //www.w3schools.com/python/python_json.asp
其次,字典必須有唯一鍵。 因此,將兩個鍵命名為 domain 是不正確的。 您可以在此處閱讀有關 Python 詞典的更多信息: https : //www.w3schools.com/python/python_dictionaries.asp
現在,我推薦以下兩種應該滿足您需求的設計:
ids = set(item["domain"] for item in data["websites"])
{
"websites": [
{
"domain": "Something.com",
"name": "Something",
"description": "A thing!"
},
{
"domain": "Thingie.com",
"name": "Thingie",
"description": "A thingie!"
},
]
}
JVM_Domains = set(data["domains"])
訪問的JVM_Domains = set(data["domains"])
{
"domains": ["Something.com","Thingie.com","Stuff.com"]
"name": "Me Domains",
"description": "A list of domains belonging to Me"
}
我希望這有幫助。 如果我遺漏了任何細節,請告訴我。
您的 JSON 有問題,重復鍵。 我不確定它是否被禁止,但我確定它的格式不正確。 除此之外,當然會給你帶來很多問題。
字典不能有重復鍵,重復鍵的返回值是什么?
所以,修復你的 JSON,像這樣,
{
"domain": ["Something", "Thingie"],
"name": "Another",
"description": "Thing"
}
猜猜看,好的格式幾乎可以解決您的問題(列表中可以有重復項):)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.