简体   繁体   中英

How to convert dictionary into a specific format

I have an output which is of below format:

(u'Columns', [{u'Type': u'string', u'Name': u'recon_c+c'}, 
              {u'Type': u'string', u'Name': u'data'}, 
              {u'Type': u'string', u'Name': u'nui'}, 
              {u'Type': u'bigint', u'Name': u'typ'}])

I wanted to convert it to below format:

recon_c+c string,
data string,
nui string,
typ bigint

How to do this using python? Since I am trying for generic solution which in if I get further more keys:values also then the code can handle.

Please let me know if any solution you guys have.

Your comma requirement slightly complicates matters, but you can use print with its optional sep argument.

T = (u'Columns', [{u'Type': u'string', u'Name': u'recon_c+c'}, 
                  {u'Type': u'string', u'Name': u'data'}, 
                  {u'Type': u'string', u'Name': u'nui'}, 
                  {u'Type': u'bigint', u'Name': u'typ'}])

print(*(' '.join((d['Name'], d['Type'])) for d in T[1]), sep=',\n')

The main point to note is that you have a tuple and the second value of your tuple is a list of dictionaries. It is this which you need to iterate.

Result

recon_c+c string,
data string,
nui string,
typ bigint

You can use a simple for loop:

#!/usr/bin/env python

l = (u'Columns', [{u'Type': u'string', u'Name': u'recon_c+c'}, 
{u'Type': u'string', u'Name': u'data'}, 
{u'Type': u'string', u'Name': u'nui'}, 
{u'Type': u'bigint', u'Name': u'typ'}])

print ",\n".join(['{} {}'.format(d['Name'], d['Type']) for d in l[-1]])

Output:

recon_c+c string,
data string,
nui string,
typ bigint

You can do it with list comprehensions in one line:

myTuple = (u'Columns', [{u'Type': u'string', u'Name': u'recon_c+c'}, 
              {u'Type': u'string', u'Name': u'data'}, 
              {u'Type': u'string', u'Name': u'nui'}, 
              {u'Type': u'bigint', u'Name': u'typ'}])

myList  =  [ print (x["Name"]+" " + x["Type"]) for x in myTuple[1] ]

Output:

recon_c+c string
data string
nui string
typ bigint

Of course you can format print any way you want.

  1 information = (
  2     u'Columns', 
  3     [
  4         {u'Type': u'string', u'Name': u'recon_c+c'},
  5         {u'Type': u'string', u'Name': u'data'}, 
  6         {u'Type': u'string', u'Name': u'nui'}, 
  7         {u'Type': u'bigint', u'Name': u'typ'}
  8     ]
  9 )
 10 
 11
 12 [print(i.get('Name'), i.get('Type')) for i in information[1]]

We can look at the dictionary as information[1] and then we can cycle through each dictionary in this list and use dict.get()

Using loop comprehension we could write:

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