【发布时间】:2019-11-09 01:55:52
【问题描述】:
我的字典:
{0: {'Id': 'd1', 'name': 'elpato', 'email': '122as@gmail.com'}, 1: {'Id': 'd2', 'name': 'petoka', 'email': 'sss@gmail.com'}}
使用它来获取字典中的名称:
for ids in [v['name'] for v in my_dict.values()]:
#subprocess.call(["...", name])
print(ids)
现在我这样做是为了生成带有在 ids 中生成的值的 jsons
这里使用faker库来创建随机数据
import faker
import json
import subprocess
for ids in [g['name'] for g in my_dict.values()]:
fake = Faker('en_US')
print(ids)
for ind in ids:
for idx in range(1):
sms = {
"user_id": ind ,
"name": fake.name(),
"email": fake.email(),
"gender": "MALE",
"mother_name": fake.name(),
"father_name": fake.name()
}
f_name = '{}.json'.format(ind)
print(f_name)
with open(f_name, 'w') as fp:
json.dump(sms, fp, indent=4)
我需要的输出:elpato.json、petoka.json。
我得到的输出:
e.json
l.json
p.json
a.json
t.json
o.json
p.json
e.json
t.json
o.json
k.json
a.json
【问题讨论】:
-
什么是
Faker?请同时添加该定义,我在my_dict中也没有看到userId键 -
更新了@DeveshKumarSingh
-
谢谢,但我仍然没有在 my_dict 中看到 userId 键,还要在文件名中说明您想要的内容,而不仅仅是提供名称
-
你宁愿需要
ind = ids而不是for ind in ids: -
@furas 它工作但如果我必须打印 10 它只打印 8。当我打印 my_dict 和 f_name 时,它显示了 10 个文件,但在本地 pc 中只有 8 个 json 无法弄清楚
标签: python json python-3.x loops dictionary