此 PHP 代码有效(下面的 json):
$usaData = json_decode(stripslashes(file_get_contents('usaJson.txt')),true);
foreach($usaData['USA']['States'] as $state){
foreach($state['Cities'] as $city){
$zipCode = $city['zipcode'];
}
}
}
我尝试在 python 中做同样的事情,但它给了我 <type 'exceptions.TypeError'>: string indices must be integers
usaData = json.loads(get_file('usaJson.txt'))
for state in usaData['USA']['States']:
for city in state['Cities']:
zipCode = city['zipcode']
我的数据结构是这样的:
{
"USA":{
"States":{
"AL":{
"Cities":[
{
"city":"auburn",
"zipcode":"36830"
},
{
"city":"birmingham",
"zipcode":"35201"
}
]
},
"AK":{
"Cities":[
{
"city":"anchorage",
"zipcode":"99501"
},
{
"city":"fairbanks",
"zipcode":"99701"
}
]
}
}
}
}
那么如何在 python 中访问邮政编码?
你的问题是迭代字典给你的是键,而不是字典中的值。所以你需要的是这样的:
for state_name in usaData['USA']['States']
for city in usaData['USA']['States'][state_name]['Cities']
print city['zipcode']
实在是太丑了
更好的版本是在字典上使用 items
函数,如下所示:
for state_name, state in usaData['USA']['States'].items():
for city in state['Cities']
print city['zipcode']
我是一名优秀的程序员,十分优秀!