字典到JSON对象转换
问题描述:
我有两个长列表(从csv中提取)两个相同的索引长度。 例子:字典到JSON对象转换
l1 = ['Apple','Tomato','Cocos'] #name of product
l2 = ['1','2','3'] #some id's
我做了我的字典用这种方法:
from collections import defaultdict
d = defaultdict(list)
for x in l1:
d['Product'].append(x)
for y in l2:
d['Plu'].append(y)
print d
这将输出:
{ '产品': '苹果', '番茄',“科科斯'],'Plu':['1','2','3']}
(Product
和Plu
是我想要的键)
现在我试图导入此为JavaScript对象是这样的:
import json
print(json.dumps(d, sort_keys=True, indent=4))
这将输出:
{
"Plu": [
"1",
"2",
"3"
],
"Product": [
"Apple",
"Tomato",
"Cocos"
]
}
但我需要的输出是这样的:
{
Product:'Apple',
Plu:'1'
},
{
Product:'Tomato',
Plu:'2'
},
{
Product:'Cocos',
Plu:'3'
}
我稍后将使用它在MongoDB中插入值。为了获得所需的输出,我需要在我的json.dump(或在我的字典?)中更改哪些内容?还有一种方法可以将输出保存在txt文件中吗? (因为我会有一个大代码)。
答
而不是使用defaultdict
(不买你在这种情况下任何东西),你就要去zip
平更好的名单,并从每对创建dict
:
[{'Product': product, 'Plu': plu} for product, plu in zip(l1, l2)]
@jherax这不是一个JS问题! – Bergi
@Bergi你是对的,谢谢修复标记+1 – jherax