python - 使用正确的键以正确的顺序检索键、值对
问题描述
我正在查看 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
,还有什么我可以尝试的吗?
解决方案
我不确定您想要实现什么,但我的理解是您正在尝试将成对打印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
再次查看字典可能是个好主意。我认为你在理解中遗漏了一些东西。
推荐阅读
- r - 是否可以控制随机森林模型中每个预测变量的分割点数?
- jira - 如何从 Unirest 请求中返回 Json 字段
- macos - MAMP Apache 端口 8888 重定向到 HTTPS,导致 SSL 错误
- mysql - 在 SQL 中处理大量用户创建的事件的最佳实践是什么?
- python-3.x - Why does np.array[None] update all values in that numpy arrray?
- typescript - 禁止 catch 中的任何错误打字稿类型
- android - Android Fragment导航动画启动时背景变为透明
- c# - 如何选择一个应用程序以使用进程控件在 c# 中启动?
- c - 在 OpenSSL 中实现 PQC 算法
- c# - 包括 Azure 源 DLL 包的调试符号