sam_7_h
sam_7_h

Reputation: 800

How to create a dictionary of dictionaries using 3 lists?

I have 3 lists. The first list contains 2 values. The second list contains multiple values including some repeating however they only repeat when they match the same position as a different value from list 1. Then the 3rd list which contains unique values for every item.

list_1 = ["Value1", "Value1", "Value2", "value1"]
list_2 = ["1111", "1234", "1111", "2468"]
list_3 = ["uniqueValue1", "uniqueValue2", "uniqueValue3", "uniqueValue4"]

I want to create 1 dictionary that has value1 and value 2 as the key, then the other 2 lists to be dictionaries inside based on the position they are in the list.

AllData = {"Value1": "Value1Dict", "Value2": "Value2Dict"}
Value1Dict = {"1111": "uniqueValue1", "1234": "uniqueValue2", "2468": "uniqueValue4"}
Value2Dict = {"1111": "UniqueValue3"}

So essentially I have ordered data that matches the position of Value1 and Value 2 but I need to separate it. If there is an easier way to do this then I'm also game for trying out that suggestion too.

Upvotes: 1

Views: 133

Answers (3)

Batman
Batman

Reputation: 8947

from collections import defaultdict

all_data = defaultdict(dict)
for outer_key, inner_key, value in zip(list_1, list_2, list_3):
    all_data[outer_key][inner_key] = value

Upvotes: 2

fsimkovic
fsimkovic

Reputation: 1128

This might be what you are looking for but note the order of your nested dictionaries might not be identical to the original list_2 and list_3 values.

In [20]: x = {k: {} for k in list_1}

In [21]: for a, b, c in zip(list_1, list_2, list_3):
    ...:     x[a][b] = c
    ...:     

In [22]: x
Out[22]: 
{'Value1': {'1111': 'uniqueValue1',
  '1234': 'uniqueValue2',
  '2468': 'uniqueValue4'},
 'Value2': {'1111': 'uniqueValue3'}}

Upvotes: 3

A. N. Other
A. N. Other

Reputation: 407

I think you virtually have the answer above. You could just nest the dictionaries in the following way

Value1Dict = {"1111": "uniqueValue1", "1234": "uniqueValue2", "2468": "uniqueValue4"}
Value2Dict = {"1111": "UniqueValue3"}
AllData = {"Value1": Value1Dict, "Value2": Value2Dict}

That should nest the dictionaries correctly!

Upvotes: 0

Related Questions