问题描述
我需要使用 json.dumps() 从 python 字典中选择特定的列。
例如
dict={"Greet":"Hello","Bike":Yamaha","Car":"Jaguar"}
r=json.dumps(Only want "Bike":Yamaha","Car":"Jaguar")
注意:不能将相同的内容存储到其他字典中并使用它。因为我想在我的代码中使用 First K,V 对。
解决方法
创建一个新字典并转储它。
d={"Greet":"Hello","Bike":Yamaha","Car":"Jaguar"}
r = json.dumps({"Bike": d["Bike"],"Car": d["Car"]})
如果您有要保留的所有键的列表,则可以使用字典推导式:
d={"Greet":"Hello","Car":"Jaguar"}
keep = ['Bike','Car']
r = json.dumps({key,d[key] for key in keep})
如果您有要省略的键的列表,也可以使用字典推导式
d={"Greet":"Hello","Car":"Jaguar"}
skip = ['Greet']
r = json.dumps({key,val for key,val in d.items() if key not in skip})
顺便说一句,不要使用 dict
作为变量名,它已经是内置函数/类的名称。
final = list(mydict.items())[1:] #extra key:value tuple list slice of the portion you need
r=json.dumps(dict(final)) #cast to dictionary and dump
输出
{"Bike": "Yamaha","Car": "Jaguar"}