简体   繁体   中英

How to convert dictionary to strings?

my_dict:

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

using this to grab name in dicts :

 for ids in [v['name'] for v in my_dict.values()]:
 #subprocess.call(["...", name])
 print(ids)

Now I'm doing this to generate jsons with values generated in ids

faker library is used here to create random data

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)

output i need: elpato.json , petoka.json.

output i'm getting:

  e.json
  l.json
  p.json
  a.json
  t.json
  o.json

  p.json
  e.json
  t.json
  o.json
  k.json
  a.json

Try this,

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

Replace with (complete code),

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)

Try this:

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

Alternatively, try below code in place of print(my_dict[k]['name']+".json") :

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

You can also try this:

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

output:

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

another option is to use:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM