Home > Blockchain >  Dynamic list creation and append values - python
Dynamic list creation and append values - python

Time:05-24

I have a input data that is parsed from a json and printing the output like this from keys like tablename,columnname,columnlength

data = ('tablename', 'abc.xyz'),('tablename','abc.xyz'),('columnname', 'xxx'),('columnname', 'yyy'),('columnlen', 55)

data[0] = 
abc.xyz
abc.xyz
abc.xyz

data[1] =
xxx
yyy
zzz

data[2] = 
20
30
60

data[0] represents tablename

data[1] represents columnname

data[2] represents column length

I have code below that does creating the empty list manually

TableName_list = []
ColumnName_list = [] 
ColumnLen_list = []

for x in data:
    if x[0] == 'tablename':
        TableName_list.append(data[0]])
    elif x[0] == 'columnname':
        ColumnName_list.append(data[1])
    elif x[0] == 'columnlen':
        ColumnLen_list.append(data[2])

I need to create a dynamic empty list respectively for each fields(tablename,column,columnlength) and append the data to that empty list in the dictionary

and my output is needed like this in a dictionary

dict =  {'TableName':TableName_list,'ColumnName':ColumnName_list,'ColumnLen':columnLength_list }

CodePudding user response:

This is probably most easily done with a defaultdict:

from collections import defaultdict
dd = defaultdict(list)

data = [
    ('tablename', 'abc.xyz'),('tablename','abc.xyz'),
    ('columnname', 'xxx'),('columnname', 'yyy'),
    ('columnlen', 55),('columnlen', 30)
]
for d in data:
    dd[d[0]].append(d[1])

Output:

defaultdict(<class 'list'>, {
    'tablename': ['abc.xyz', 'abc.xyz'],
    'columnname': ['xxx', 'yyy'],
    'columnlen': [55, 30]
})

If the case of the names in the result is important, you could use a dictionary to translate the incoming names:

aliases = { 'tablename' : 'TableName', 'columnname' : 'ColumnName', 'columnlen' : 'ColumnLen' }
for d in data:
    dd[aliases[d[0]]].append(d[1])

Output:

defaultdict(<class 'list'>, {
    'TableName': ['abc.xyz', 'abc.xyz'],
    'ColumnName': ['xxx', 'yyy'], 
    'ColumnLen': [55, 30]
})

CodePudding user response:

I suggest to make a dictionary directly, something look like this:

out_dict = {}
for x in data:
  key = x[0]
  if key in out_dict.keys():
    out_dict[key] = out_dict[key].append(x[1])
  else:
    out_dict[key] = [x[1]]

CodePudding user response:

using pandas:

import pandas as pd

>>> pd.DataFrame(data).groupby(0)[1].apply(list).to_dict()
'''
{'columnlen': [55, 30],
 'columnname': ['xxx', 'yyy'],
 'tablename': ['abc.xyz', 'abc.xyz']}
  • Related