如何将字典转换为字符串?

时间:2019-06-27 05:15:28

标签: python json python-3.x loops dictionary

my_dict:

{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)

现在我正在执行此操作,以使用ID中生成的值生成JSON

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

3 个答案:

答案 0 :(得分:1)

尝试一下

>>> my_dict = {0: {'Id': 'd1', 'name': 'elpato', 'email': '122as@gmail.com'}, 1: {'Id': 'd2', 'name': 'petoka', 'email': 'sss@gmail.com'}}
>>> ", ".join('{}.json'.format(v) for ik,iv in d.items() for k,v in iv.items() if k == 'name')
'elpato.json, petoka.json' # output in string form

替换为(完整代码)

import faker
import json
import subprocess

my_dict = {0: {'Id': 'd1', 'name': 'elpato', 'email': '122as@gmail.com'}, 1: {'Id': 'd2', 'name': 'petoka', 'email': 'sss@gmail.com'}}

f_names = [(ik, '{}.json'.format(v)) for ik,iv in my_dict.items() for k,v in iv.items() if k == 'name']
for values in f_names:
    fake = Faker('en_US')
    ind,f_name = [*values]
    sms =  {
            "user_id": ind ,
            "name": fake.name(),
            "email": fake.email(),
            "gender": "MALE",
            "mother_name": fake.name(),
            "father_name": fake.name()
            }
    with open(f_name, 'w') as fp:
        json.dump(sms, fp, indent=4)

答案 1 :(得分:0)

尝试一下:

my_dict = {0: {'Id': 'd1', 'name': 'elpato', 'email': '122as@gmail.com'}, 1: {'Id': 'd2', 'name': 'petoka', 'email': 'sss@gmail.com'}}
for k, v in my_dict.items():
    print(my_dict[k]['name']+".json")

或者,尝试下面的代码代替print(my_dict[k]['name']+".json")

print('{}.json'.format(my_dict[k]['name']))

您也可以尝试以下方法:

for value in my_dict.values():
    print('{}.json'.format(value['name']))

输出:

elpato.json
petoka.json

答案 2 :(得分:0)

In [14]: ', '.join(f"{i['name']}.json" for i in my_dict.values())
Out[14]: 'elpato.json, petoka.json'

另一个选择是使用:

You can use print(f"{f_name}.josn", end = ', ')