[英]How to iterate list items to store as a dictionary and write it to json?
我有一个列表,我想迭代并写入它以写入 json。 例如:
lis_1 = ['fellow','hello','yellow']
现在我将它存储为字典:
items_main = {}
new_list = []
result_2 = {}
items = {}
lis_1 = ['fellow','hello','yellow']
for i,l in enumerate(lis_1):
key, value = str(i+1), str(lis_1[i])
items[key] = value
new_list.append(items)
for d in new_list:
result_2.update(d)
print(result_2)
我也很少有其他相同的变量
name = 'buddy'
year = 2008
sample = {
"FDRID1":{
"1": {
"Property_name":{
"1": str(name )
},
items_main['Building Highlights'] = result_2
"Year":{
"1":str(year)
}
}
}
}
with open(out_file, 'w') as fp:
json.dump(sample, fp)
预期输出:
"FDRID1":{
"1": {
"Property_name":{
"1": "buddy"
},
"BuildingHighlights":{
"1":"fellow",
"2":"hello",
"3":"yellow"
},
"Year":{
"1":'2008'
}
}
}
此外,如果 **lis_1 = ['']**ie, (empty)。输出必须是:
"FDRID1":{
"1": {
"Property_name":{
"1": "buddy"
},
"BuildingHighlights":{
"1":"",
"
},
"Year":{
"1":'2008'
}
}
}
我不太确定我是否完全理解你想要做什么:
result_1 = {str(i): v for i, v in enumerate(lis_1, 1)} if lis_1 else {'1', ''}
您的空列表示例输出不是有效的 json,因为它有一个虚假的"
- 假设这只是一个编辑错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.