0

Say I have dictionaries like this :

{'AccountNum': '873627867348', 'userID': 'abc'}
{'AccountNum': '873627867348', 'userID': 'def'}
{'AccountNum': '038683828978', 'userID': 'ghi'}
{'AccountNum': '581889263266', 'userID': 'jkl'}
{'AccountNum': '581889263266', 'userID': 'mno'}
{'AccountNum': '581889263266', 'userID': 'pqr'}

I need to convert this into a list such that both the keys and values are printed. Actually I am using Django as the web framework. I need to return a list and render it to my template page, where I will be displaying the user id and accountnum in the rows of the table.

preferred output sample:

['AccountNum', '873627867348', 'userID', 'abc']
Slam
  • 8,112
  • 1
  • 36
  • 44
Siddharth Singh
  • 105
  • 3
  • 15

2 Answers2

3

If you want to get the keys as list, use:

list( {'AccountNum': '873627867348', 'userID': 'abc'} )
#['AccountNum', 'userID']

for the values:

list( v for k, v in {'AccountNum': '873627867348', 'userID': 'abc'}.items() )
#['873627867348', 'abc']

for both:

list( {'AccountNum': '873627867348', 'userID': 'abc'}.items() )
#[('AccountNum', '873627867348'), ('userID', 'abc')]

if you don't like it with tuple here an approach with more then one line:

def dictToList(d):
    l = []
    for k, v in  d.items():
        l.append(k)
        l.append(v)
    return l
dictToList({'AccountNum': '873627867348', 'userID': 'abc'})
# ['AccountNum', '873627867348', 'userID', 'abc']
Skandix
  • 1,916
  • 6
  • 27
  • 36
0

How about this using list comprehension:

[a for a in(b for a in data.items() for b in a)]

Input :

data={'AccountNum': '873627867348', 'userID': 'abc'}

Output :

['userID', 'abc', 'AccountNum', '873627867348']   

You can also use Regular expression,

import re
data={'AccountNum': '873627867348', 'userID': 'abc'}

re.findall(r"\'(.*?)\'", str(data) )

Output :

['userID', 'abc', 'AccountNum', '873627867348']
khelili miliana
  • 3,730
  • 2
  • 15
  • 28