我需要找到JSON文件中出现次数最多的前3个键。我发现该文件具有41个唯一键(数千个对象中的唯一键),现在我必须找出每个键在JSON文件中出现的次数,并返回前3个键以及每个键重复的次数降序排列。
这是我已经完成的代码。在这里,我设法从所有对象中获得了一定数量的唯一键。
import json
with open('users.json') as f:
data = json.load(f) #loads JSON data into dictionary
unique_users = set(item["user_id"] for item in data) # gives unique
users in data
users = list(unique_users) # 41 users list
预期的结果格式如下:
1. user234: 456
2. user245: 345
3. user 3453: 154
答案 0 :(得分:1)
import json
from collections import Counter
with open('users.json') as f:
data = json.load(f)
user_counter = Counter(item["user_id"] for item in data)
for i, (user, count) in enumerate(user_counter.items()):
print(f"{i}. {user}: {count}")
答案 1 :(得分:0)
您可以使用collections.Counter创建频率字典,然后使用Counter.most_common从该频率表中选择前3个元素
from collections import Counter
import json
#Get dictionary
with open('users.json') as f:
data = json.load(f) #loads JSON data into dictionary
#Get all user_id from the dictionary and create a frequency counter
counter = Counter(item["user_id"] for item in data)
#Get top 3 using most_common
top_3 = counter.most_common(3)
for key, value in top_3:
print('{}: {}'.format(key,value))
例如
from collections import Counter
from itertools import product
import json
#Assuming these are the list of user id's we got from json
counter = Counter(['user_1','user_1','user_1','user_1','user_2','user_2','user_2','user_3','user_3','user_4' ])
#Get top 3 using most_common
top_3 = counter.most_common(3)
for key, value in top_3:
print('{}: {}'.format(key,value))
输出将为
user_1: 4
user_2: 3
user_3: 2