python idiom for creating dict of dict of list

  • Last Update :
  • Techknowledgy :

Last Updated : 11 Mar, 2019

Output:

TypeError: unhashable type: 'list'

Suggestion : 2

The simplest way is to just create new dict literals for the inner dict:

outerdict = {}
outerdict[name] = {
   type_: [v1, v2, v3]
}

or you could use dict.setdefault() to materialize the inner dict as needed:

outerdict.setdefault(name, {})[type_] = [v1, v2, v3]

or you could use collections.defaultdict() to have it handle new values for you:

from collections
import defaultdict

outerdict = defaultdict(dict)
outerdict[name][type_] = [v1, v2, v3]

The Python 2 version would be:

with open(filename) as infh:
   for line in infh:
   name, _, type_, values = line.split(None, 3)
outerdict[name][type_] = map(int, values.split())

To have the inner-most list accumulate all values for repeated (name, type_) key combinations, you'll need to use a slightly more complex defaultdict setup; one that produces an inner defaultdict() set to produce list values:

outerdict = defaultdict(lambda: defaultdict(list))
with open(filename) as infh:
   for line in infh:
   name, _, type_, values = line.split(None, 3)
outerdict[name][type_].extend(map(int, values.split()))

Another excellent way is to do the following:

from collections
import defaultdict

d = defaultdict(lambda: defaultdict(list))

# eg.
d["x"]["y"].append(100)
1._
def make_strukture(lst_of_str):
   result = {}
for i in my_strs:
   data = i.split()
if data[0] in result.keys(): continue #Only one first key
for foo, bar
result[data[0]] = {}
#Create first key foo, bar - level
result[data[0]][data[2]] = list(data[3: ]) #Skip kk and create second key with list
return result

#Below more comples data structure:
   my_strs = ["foo kk type1 1 2 3", "foo kk type2 1 2 3", "bar kk type2 3 5 1"]
print make_strukture(my_strs)

Print result:

{
   'foo': {
      'type1': ['1', '2', '3']
   },
   'bar': {
      'type2': ['3', '5', '1']
   }
}

Instead of using a defaultdict, you can use a normal dict with reduce and dict.setdefault. Here's an example that could be wrapped into a function:

text_data = ""
"foo kk type1 1 2 3
bar kk type2 3 5 1 ""
"

data = [line.split() for line in text_data.splitlines()]
#[['foo', 'kk', 'type1', '1', '2', '3'], ['bar', 'kk', 'type2', '3', '5', '1']]

var1 = {}
for row in data:
   # row[: 2] everything before leaf, [2] is the leaf, row[3: ] remainder of 'values'
reduce(lambda a, b: a.setdefault(b, {}), row[: 2], var1)[2] = row[3: ]
# {
   'foo': {
      'kk': {
         2: ['1', '2', '3']
      }
   },
   'bar': {
      'kk': {
         2: ['3', '5', '1']
      }
   }
}

Then, wrap it up into a function with an optional converter for the values, eg:

def nested_dict(sequences, n, converter = lambda L: L):
   ret = {}
for seq in sequences:
   reduce(lambda a, b: a.setdefault(b, {}), seq[: n - 1], ret)[n] = map(converter, seq[n: ])
return ret

nested_dict(data, 2)
# {
   'foo': {
      2: ['type1', '1', '2', '3']
   },
   'bar': {
      2: ['type2', '3', '5', '1']
   }
}
nested_dict(data, 3)
# {
   'foo': {
      'kk': {
         3: ['1', '2', '3']
      }
   },
   'bar': {
      'kk': {
         3: ['3', '5', '1']
      }
   }
}
nested_dict(data, 3, int)
# {
   'foo': {
      'kk': {
         3: [1, 2, 3]
      }
   },
   'bar': {
      'kk': {
         3: [3, 5, 1]
      }
   }
}
#...

Suggestion : 3

In this program, we will see how to convert a dictionary of lists to list of dictionaries.,In this program, we will see how to create a dictionary of lists to the dataframe.,In this program, we will discuss how to create a dictionary of lists.,Python dictionary of lists to list of dictionaries

Here is the Syntax of the default dict() method

defaultdict(default_factory)

Source Code:

from collections
import defaultdict

my_new_list = [('Micheal', 18), ('George', 91), ('Oliva', 74)]
new_dictionary = defaultdict(list)

for new_k, new_val in my_new_list:
   new_dictionary[new_k].append(new_val)

print("Dictionary of lists", new_dictionary)

Example:

student_info = {
   'Student_id': [85, 47, 49],
   'Student_age': [91, 116, 913]
}

print("values from list1:", student_info['Student_id'])
print("values from second list:", student_info['Student_age'])

Suggestion : 4

In this article, you’ll learn about nested dictionary in Python. More specifically, you’ll learn to create nested dictionary, access elements, modify them and so on with the help of examples.,In Python, a nested dictionary is a dictionary inside a dictionary. It's a collection of dictionaries into one single dictionary.,In the above program, we delete both the internal dictionary 3 and 4 using del from the nested dictionary people. Then, we print the nested dictionary people to confirm changes.,Here, the nested_dict is a nested dictionary with the dictionary dictA and dictB. They are two dictionary each having own key and value.

In Python, a dictionary is an unordered collection of items. For example:

dictionary = {
   'key': 'value',
   'key_2': 'value_2'
}

In Python, a nested dictionary is a dictionary inside a dictionary. It's a collection of dictionaries into one single dictionary.

nested_dict = {
   'dictA': {
      'key_1': 'value_1'
   },
   'dictB': {
      'key_2': 'value_2'
   }
}

Example 1: How to create a nested dictionary

people = {
   1: {
      'name': 'John',
      'age': '27',
      'sex': 'Male'
   },
   2: {
      'name': 'Marie',
      'age': '22',
      'sex': 'Female'
   }
}

print(people)

Example 2: Access the elements using the [] syntax

people = {
   1: {
      'name': 'John',
      'age': '27',
      'sex': 'Male'
   },
   2: {
      'name': 'Marie',
      'age': '22',
      'sex': 'Female'
   }
}

print(people[1]['name'])
print(people[1]['age'])
print(people[1]['sex'])

Example 3: How to change or add elements in a nested dictionary?

people = {
   1: {
      'name': 'John',
      'age': '27',
      'sex': 'Male'
   },
   2: {
      'name': 'Marie',
      'age': '22',
      'sex': 'Female'
   }
}

people[3] = {}

people[3]['name'] = 'Luna'
people[3]['age'] = '24'
people[3]['sex'] = 'Female'
people[3]['married'] = 'No'

print(people[3])

Suggestion : 5

create a list of dictionaries,append a dictionary to the list,Let’s update the above Python list of dictionaries in all the above discussed ways through Python code.,In this tutorial, we are going to discuss a list of dictionaries in Python. We will discuss how to

# Defining a list of dictionaries in Python
ls_dict = [{
      'py': 'Python',
      'mat': 'MATLAB',
      'cs': 'Csharp'
   },
   {
      'A': 65,
      'B': 66,
      'C': 67
   },
   {
      'a': 97,
      'b': 98,
      'c': 99
   }
]

# Printing the results
print(ls_dict)

# Validating the type of 'ls_dict'
and its element
print(type(ls_dict))
print(type(ls_dict[0]))
# Defining a list of dictionaries in Python
ls_dict = [{
      'py': 'Python',
      'mat': 'MATLAB',
      'cs': 'Csharp'
   },
   {
      'A': 65,
      'B': 66,
      'C': 67
   },
   {
      'a': 97,
      'b': 98,
      'c': 99
   },
]

# Printing the given list of dictionaries
print("Given Python list of dictionaries:\n", ls_dict)

# Creating a new Python dictionary
ds = {
   'AskPython': "Python",
   'JournalDev': "ALL",
   'LinuxforDevices': "Linux"
}

# Appending the list of dictionaries with the above dictionary
# Using append() method
ls_dict.append(ds)

# Printing the appended list of dictionaries
print("Appended Python list of dictionaries:\n", ls_dict)
# Defining a list of dictionaries in Python
ls_dict = [{
      'A': 65,
      'B': 66,
      'C': 67
   },
   {
      'py': 'Python',
      'mat': 'MATLAB',
      'cs': 'Csharp'
   },
   {
      'a': 97,
      'b': 98,
      'c': 99
   }
]

# Printing the given list of dictionaries
print("Given Python list of dictionaries:\n", ls_dict)

# Accessing and printing the key: value pairs of a list of dictionary
print(ls_dict[1])
print(ls_dict[1]['py'])
# Defining a list of dictionaries in Python
ls_dict = [{
      'A': 65,
      'B': 66,
      'C': 67
   },
   {
      'py': 'Python',
      'mat': 'MATLAB',
      'cs': 'Csharp'
   },
   {
      'a': 97,
      'b': 98,
      'c': 99
   }
]

# Printing the given list of dictionaries
print("Given Python list of dictionaries:\n", ls_dict)

# Adding a new key: value pair to the 1 st dictionary in the list
ls_dict[0]['new_key'] = 'new_value'

# Updating an existing key: value pair in the 2n d dictionary in the list
ls_dict[1]['py'] = 'PYTHON'

# Deleting an existing key: value pair from the 3 rd dictionary in the list
del ls_dict[2]['b']

# Printing the updated list of dictionaries
print("Updated Python list of dictionaries:\n", ls_dict)