我有一个要处理的JSON文件,我知道这听起来很基本,但是我的问题是,基于User1 +国家,我如何根据以下列出的国家/地区列出所有其他用户:用户1
编辑:获取名称而不是用户ID,我意识到我无法使用键,值,该如何解决?
axios
这是我到目前为止所做的
{
"user1":{
"Country":[
"China, USA, Nepal"
],
"Name": [
"Lisbon"
],
},
"user2":{
"Country":[
"Sweden, China, USA"
],
"Name": [
"Jade"
],
},
"user3":{
"Country":[
"India, China, USA"
],
"Name": [
"John"
],
}
}
答案 0 :(得分:2)
那会做你想要的:
def getId(name):
for userId, v in data.items():
if v['Name'] == name:
return userId;
id = getId(userName)
for k, v in data.items():
if any(x in data[id]['Country'] for x in v['Country']):
print(k)
但是仅当您修复json时。您的国家/地区列表只有一个字符串。 [“ China”,“ USA”,“ Nepal”]代替[“ China,USA,Nepal”]
答案 1 :(得分:1)
使用json,您可以使用
set.intersection
方法:
userName= raw_input("Enter user's name: ")
with open('listOfUsers.json') as f:
data = json.load(f)
# get username Country
user_country = data.get(username, {}).get("Country", [])[0].split()
user_country_set = set(user_country)
# then filter all users having same Country
users = [u for u, v in data.items() if set(v["Country"][0].split()).intersection(user_country_set) ]
但是,如果您可以控制输入的json格式,我建议使用:
"Country":[
"China", "USA", "Nepal"
]
相反,它将大大简化代码:
user_country = data.get(username, {}).get("Country", [])
user_country_set = set(user_country)
# then filter all users having same Country
users = [user for user, d in data.items() if set(d.get("Country", [])).intersection(user_country_set) ]