OAK
OAK

Reputation: 3166

Join list of list and another list?

I am looking to read one list which consists of columns names and another list of lists which consists of data which needs to be mapped to the columns. Each list in the list of list is one row of data to later be push into the database.

I've tried to use the following code to join these two lists: dict(zip( column_names, data)) but I recieve an error:

TypeError unhashable type: 'list'

How would I join a list of lists and another list together to a dict?

column_names = ['id', 'first_name', 'last_name', 'city', 'dob']

data = [
     ['1', 'Mike', 'Walters', 'New York City', '1998-12-01'],
     ['2', 'Daniel', 'Strange', 'Baltimore', '1992-08-12'],
     ['3', 'Sarah', 'McNeal', 'Miami', '1990-05-05'],
     ['4', 'Steve', 'Breene', 'Philadelphia', '1988-02-06']
]

The result I'm seeking is:

dict_items = {{'id': '1', 'first_name': 'Mike', 'last_name': 'Walters',
               'city': 'New York City', 'dob': '1998-12-01'},
              {'id': '2', ...}}

Later looking to push this dict of dicts to the database with SQLAlchemy.

Upvotes: 2

Views: 395

Answers (7)

Fuji Komalan
Fuji Komalan

Reputation: 2047

column_names = ['id', 'first_name', 'last_name', 'city', 'dob']

data = [
     ['1', 'Mike', 'Walters', 'New York City', '1998-12-01'],
     ['2', 'Daniel', 'Strange', 'Baltimore', '1992-08-12'],
     ['3', 'Sarah', 'McNeal', 'Miami', '1990-05-05'],
     ['4', 'Steve', 'Breene', 'Philadelphia', '1988-02-06']
]

destinationList = []

for value in data: 
  destinationList.append(dict(zip(column_names,value)))
print(destinationList)
#
# zip(column_names,value)
# [('id', '1'), ('first_name', 'Mike') , ('last_name', 'Walters'), ('city', 'New York City'),('dob', '1998-12-01')]]
# dict(zip(column_names,value))
# {'last_name': 'Walters', 'dob': '1998-12-01','id': '1','first_name': 'Mike','city': 'New York City'}

Upvotes: 0

chejos
chejos

Reputation: 11

Two simple for-loops:

column_names = ['id', 'first_name', 'last_name', 'city', 'dob']

data = [
    ['1', 'Mike', 'Walters', 'New York City', '1998-12-01'],
    ['2', 'Daniel', 'Strange', 'Baltimore', '1992-08-12'],
    ['3', 'Sarah', 'McNeal', 'Miami', '1990-05-05'],
    ['4', 'Steve', 'Breene', 'Philadelphia', '1988-02-06']
        ]

db_result = []
for data_row in data:
  new_db_row = {}
  for i, data_value in enumerate(data_row):
    new_db_row[column_names[i]] = data_value
  result.append(new_db_row)
print(result)

First For statement loops over all data rows. The second uses enumerate to separate the index(i) and the data_value of the rows. The index is used to extract the column names from the list column_names.

I hope this explanation does not make it more complicated. Following the printed result.

[{'id': '1', 'first_name': 'Mike', 'last_name': 'Walters', 'city': 'New York City', 'dob': '1998-12-01'}, {'id': '2', 'first_name': 'Daniel', 'last_name': 'Strange', 'city': 'Baltimore', 'dob': '1992-08-12'}, {'id': '3', 'first_name': 'Sarah', 'last_name': 'McNeal', 'city': 'Miami', 'dob': '1990-05-05'}, {'id': '4', 'first_name': 'Steve', 'last_name': 'Breene', 'city': 'Philadelphia', 'dob': '1988-02-06'}]

Upvotes: 1

efajardo
efajardo

Reputation: 797

All the other answers above worked fine. Just for the sake of completeness you could also use pandas (and it might be convenient if your data is coming from say a csv file).

Just create a data frame with your data and then convert it to dict:

import pandas as pd
df = pd.DataFrame(data, columns=column_names)
df.to_dict(orient='records')

Upvotes: 1

Vivek Sable
Vivek Sable

Reputation: 10223

zip will not work in your case, because its map one to one input arguments.

Zip Documentation

Demo:

>>> l1 = ["key01", "key02", "key03"]
>>> l2 = ["value01", "value02", "value03"]
>>> zip(l1, l2)
[('key01', 'value01'), ('key02', 'value02'), ('key03', 'value03')]
>>> dict(zip(l1, l2))
{'key01': 'value01', 'key02': 'value02', 'key03': 'value03'}
>>> 

Use normal iteration and list append method to create final output:

Demo:

>>> list_data_items  = []
>>> for item in data:
...    list_data_items.append(dict(zip(column_names, item)))
... 

Upvotes: 1

Hackaholic
Hackaholic

Reputation: 19753

Using Pandas:

>>> column_names
['id', 'first_name', 'last_name', 'city', 'dob']
>>> data
[['1', 'Mike', 'Walters', 'New York City', '1998-12-01'], ['2', 'Daniel', 'Strange', 'Baltimore', '1992-08-12'], ['3', 'Sarah', 'McNeal', 'Miami', '1990-05-05'], ['4', 'Steve', 'Breene', 'Philadelphia', '1988-02-06']]
>>> import pandas as pd
>>> pd.DataFrame(data, columns=column_names).T.to_dict().values()
[{'dob': '1998-12-01', 'city': 'New York City', 'first_name': 'Mike', 'last_name': 'Walters', 'id': '1'}, {'dob': '1992-08-12', 'city': 'Baltimore', 'first_name': 'Daniel', 'last_name': 'Strange', 'id': '2'}, {'dob': '1990-05-05', 'city': 'Miami', 'first_name': 'Sarah', 'last_name': 'McNeal', 'id': '3'}, {'dob': '1988-02-06', 'city': 'Philadelphia', 'first_name': 'Steve', 'last_name': 'Breene', 'id': '4'}]

Upvotes: 0

timgeb
timgeb

Reputation: 78760

Since you want to construct multiple dictionaries, you have to zip your column names with each list in data and pass the result to the dict constructor. Your result dict_items also needs to be a collection that can store unhashable types such as dictionaries. We cannot use a set for this (which you say you are seeking), but we can use a list (or a tuple).

Employ a simple list comprehension in order to build one dictionary for each sublist in data.

>>> [dict(zip(column_names, sublist)) for sublist in data]
[{'dob': '1998-12-01', 'city': 'New York City', 'first_name': 'Mike', 'last_name': 'Walters', 'id': '1'}, {'dob': '1992-08-12', 'city': 'Baltimore', 'first_name': 'Daniel', 'last_name': 'Strange', 'id': '2'}, {'dob': '1990-05-05', 'city': 'Miami', 'first_name': 'Sarah', 'last_name': 'McNeal', 'id': '3'}, {'dob': '1988-02-06', 'city': 'Philadelphia', 'first_name': 'Steve', 'last_name': 'Breene', 'id': '4'}]

I also assumed that {'id':'2'} in your expected result is a typo.

Upvotes: 0

fafl
fafl

Reputation: 7385

You can create a list of key-value-pairs like this:

result = [dict(zip(column_names, row)) for row in data]

Note the brackets are not curly like you specified.

Upvotes: 6

Related Questions