Home > Net >  How can I create a dictionary from two lists, one list is the keys, the other contains nested values
How can I create a dictionary from two lists, one list is the keys, the other contains nested values

Time:07-27

I have two lists:

list_values = [['James', '40', 'Engineer'], ['Mary', '30', 'Nurse]] 

and

keys = ['Name', 'Age' 'Profession'].

My intention is to create a dictionary with the following output:

{'name': 'James', 'Age': '40', 'Profession': 'Engineer'},{'name': 'Mary', 'Age': '30', 'Profession': 'Nurse'}

However, my code only gives me contents from the first dictionary generated, that is:

{'name': 'James', 'Age': '40', 'Profession': 'Engineer'}

Here is the code:

dict_content = {}
for person in list_values:
    for val in range(len(keys)):
        key = keys[val]
        value = person[val]
        dict_content[key] = value
print(dict_content)

For instance, I do not know why my code only runs the inner for loop and does not come back to pick the second nested list in the first for loop. Am interested in knowing why my code is wrong for I have spend almost a day trying to figure the problem to no success.

CodePudding user response:

Just a one-liner does it:

dct = [dict(zip(keys,vals)) for vals in list_values]

Output:

[{'Name': 'James', 'Age': '40', 'Profession': 'Engineer'}, {'Name': 'Mary', 'Age': '30', 'Profession': 'Nurse'}]

CodePudding user response:

list_values = [['James', '40', 'Engineer'], ['Mary', '30', 'Nurse']] 
keys = ['Name', 'Age', 'Profession']
dict = {k:[] for k in keys}
for person in list_values:
    for i in range(len(keys)):
        dict[keys[i]].append(person[i])

In this case a dataframe can be easily generated with pd.DataFrame.from_dict(dict).

CodePudding user response:

In python, dictionary keys must be unique, meaning you can't really have multiple names and ages inside one dictionary. Instead, you can make a list of these dictionaries. You can also combine two lists into a dict using the zip function, which returns a new list containing tuples of the corresponding indexes. So zip([1, 2], [3, 4]) would return [(1, 3), (2, 4)]. You can then construct a dictionary from that using dict(zipped_list) With all that in mind, the code to do what you want is this

list_values = [['James', '40', 'Engineer'], ['Mary', '30', 'Nurse']] 
keys = ['Name', 'Age', 'Profession']
dict_list = [dict(zip(keys, i)) for i in list_values]
  • Related