首页 > 解决方案 > 使用正确的键以正确的顺序检索键、值对

问题描述

我正在查看 W3 学校的示例,将 JSON 转换为 Python 部分

https://www.w3schools.com/python/python_json.asp

import json

# some JSON:
x =  '{ "name":"John", "age":30, "city":"New York"}'

# parse x:
y = json.loads(x)

# the result is a Python dictionary:
print(y["age"])

我正在尝试使用键值对来打印

import json

def emp_data(**args):
    emp= '{ "name":"John", "age":30, "city":"New York"}'

    # parse x:
    jsonObject = json.loads(emp)


    # the result is a Python dictionary:
    for key in jsonObject:
        for value in jsonObject['name'], ['city'],['age']:
            print()
    print(key, jsonObject['name'], jsonObject['city'],jsonObject['age'])

emp_data()

结果不一致并且没有打印所有的键。

age John New York 30

我尝试将它们分开并不能解决问题

print(key, jsonObject['name'])  

print(key, jsonObject['city'])  

print(key, jsonObject['age'])   

我试过了**args,还有什么我可以尝试的吗?

标签: pythonjsondictionary

解决方案


我不确定您想要实现什么,但我的理解是您正在尝试将成对打印key-value在一起。正如@jonrsharpe 提到的,字典不是有序结构,问题在于循环。

如果要打印出key-value对,可以执行以下操作:

import json

def emp_data(**args):
   emp= '{ "name":"John", "age":30, "city":"New York"}'

   # parse x:
   jsonObject = json.loads(emp)

   # the result is a Python dictionary:
   # As @Iluvatar mentioned, you can iterate over both key and value 

   for key,val in jsonObject.items():
      print key + ',' + str(jsonObject[key])

结果将是(按某种顺序):

city, New York
age, 30
name, John

再次查看字典可能是个好主意。我认为你在理解中遗漏了一些东西。


推荐阅读