请参阅以下从API获取的JSON。
my_json =
{
"cities":[
{
"portland":[
{"more_info":[{"rank": "3", "games_played": "5"}
],
"team_name": "blazers"
},
{
"cleveland":[
{"more_info":[{"rank": "2", "games_played": "7"}
],
"team_name": "cavaliers"
}
]
}
我想使用" team_name"从my_json创建一个新字典。作为关键和"排名"作为价值。
像这样:{'开拓者':3,'骑士':2,'公牛':7}
我不确定如何完成这个...我可以返回一个城市列表,我可以返回一个排名列表,但它们最终是两个单独的列表,没有任何关系,我'我不知道如何将两者联系起来。
任何帮助都将受到赞赏(我也愿意在列表中组织此信息,而不是直接判断是否更容易)。
如果我这样做:
results_dict = {}
cities = my_json.get('cities', [])
for x in cities:
for k,v in x.items():
print k, v
它返回:
team_name blazers
portland [{"rank": "3", "games_played": "5"}
team_name cavaliers
cavaliers [{"rank": "2", "games_played": "7"}
答案 0 :(得分:0)
如果您想要使用cities
列表和ranks
列表并将它们合并,可以使用zip()
和词典理解:
output = {city: rank for city, rank in zip(cities, ranks)}
答案 1 :(得分:0)
有效JSON如下:
{
"cities":[
{
"portland":[
{"more_info":
[{"rank": "3", "games_played": "5"}],
"team_name":
"blazers"
}
]
},
{
"cleveland":[
{"more_info":
[{"rank": "2", "games_played": "7"}],
"team_name":
"cavaliers"
}
]
}
]
}
这部分代码会返回您想要的所有内容,但我会尝试编写更易读的代码,而不是:
results_dict = {}
cities = my_json.get('cities', [])
for x in cities:
for k,v in x.items():
for element in v:
team = element.get('team_name', '')
meta_data = element.get('more_info', [])
for item in meta_data:
rank = item.get('rank')
results_dict.update({team: rank})
>>> results_dict
{'blazers': '3', 'cavaliers': '2'}
答案 2 :(得分:0)
那是什么API? JSON结构(如果pivanchy正确)似乎不必要地嵌套在列表中。 (一个城市可以拥有多个团队吗?可能是的。但是,一个团队可以拥有多个级别吗?)
但是对于体育而言,这里有一个巨大的词典理解来提取你想要的数据:
{ team['team_name']: team['more_info'][0]['rank']
for ((team,),) in (
city.values() for city in my_json['cities']
)
}
答案 3 :(得分:0)
json似乎缺少一些结束括号。添加它们后我得到了这个:
my_json = {
"cities": [
{"portland":[
{"more_info":[{"rank": "3", "games_played": "5"}],"team_name": "blazers"}]},
{"cleveland":[{"more_info":[{"rank": "2", "games_played": "7"}],"team_name": "cavaliers"}]}
]
}
鉴于结构非常嵌套,以下代码将提取您想要的数据,但它非常混乱:
results = {}
for el in my_json["cities"]:
name = el.keys()[0]
rank = el.values()[0][0]["more_info"][0]["rank"]
results[name] = rank
print results
哪个会给你:
{'portland': '3', 'cleveland': '2'}