How do you create nested dict in Python?
A nested dict is a dictionary within a dictionary. A very simple thing.
>>> d = {}
>>> d['dict1'] = {}
>>> d['dict1']['innerkey'] = 'value'
>>> d['dict1']['innerkey2'] = 'value2'
>>> d
{'dict1': {'innerkey': 'value', 'innerkey2': 'value2'}}
You can also use a defaultdict
from the collections
package to facilitate creating nested dictionaries.
>>> import collections
>>> d = collections.defaultdict(dict)
>>> d['dict1']['innerkey'] = 'value'
>>> d # currently a defaultdict type
defaultdict(<type 'dict'>, {'dict1': {'innerkey': 'value'}})
>>> dict(d) # but is exactly like a normal dictionary.
{'dict1': {'innerkey': 'value'}}
You can populate that however you want.
I would recommend in your code something like the following:
d = {} # can use defaultdict(dict) instead
for row in file_map:
# derive row key from something
# when using defaultdict, we can skip the next step creating a dictionary on row_key
d[row_key] = {}
for idx, col in enumerate(row):
d[row_key][idx] = col
According to your comment:
may be above code is confusing the question. My problem in nutshell: I
have 2 files a.csv b.csv, a.csv has 4 columns i j k l, b.csv also has
these columns. i is kind of key columns for these csvs'. j k l column
is empty in a.csv but populated in b.csv. I want to map values of j k
l columns using 'i` as key column from b.csv to a.csv file
My suggestion would be something like this (without using defaultdict):
a_file = "path/to/a.csv"
b_file = "path/to/b.csv"
# read from file a.csv
with open(a_file) as f:
# skip headers
f.next()
# get first colum as keys
keys = (line.split(',')[0] for line in f)
# create empty dictionary:
d = {}
# read from file b.csv
with open(b_file) as f:
# gather headers except first key header
headers = f.next().split(',')[1:]
# iterate lines
for line in f:
# gather the colums
cols = line.strip().split(',')
# check to make sure this key should be mapped.
if cols[0] not in keys:
continue
# add key to dict
d[cols[0]] = dict(
# inner keys are the header names, values are columns
(headers[idx], v) for idx, v in enumerate(cols[1:]))
Please note though, that for parsing csv files there is a csv module.
How to create a nested dictionary in python with 6 lists
Maybe something like:
out = {k: {k1: v1, k2: v2} for k, k1, v1, k2, v2 in zip(a, b, c, d, e)}
If we want to use excessive number of zip
s, we could also do:
out = {k: dict(v) for k,v in zip(a, zip(zip(b, c), zip(d, e)))}
Output:
{'A':{1 :9, 0:11} , 'B':{2:8, 3:13}, 'C':{3:7, 5:13} , 'D':{4:6, 7:15}}
How to create nested dictionaries PYTHON
Use a list comprehension. Iterate over the zipped lists and create the nested dictionaries:
a = ['A', 'B', 'C', 'D']
b = [1, 2, 3, 4]
c = ['N1', 'N2', 'N3', 'N4']
>>> [{k1: {k2: v}} for k1, v, k2 in zip(a, b, c)]
[{'A': {'N1': 1}}, {'B': {'N2': 2}}, {'C': {'N3': 3}}, {'D': {'N4': 4}}]
How to create a nested dictionary from a list of lists
Here is a solution you can give it a try,
print({
k: v for k, v in enumerate(dict(zip(val[0], v)) for v in val[1:])
})
{0: {'a': 1, 'b': 'a', 'c': 'x'}, 1: {'a': 2, 'b': 'b', 'c': 'y'}}
Create a nested Dictionary with two dictionaries
You can use defaultdict
here. multi
need not be sorted.
from collections import defaultdict
out=defaultdict(dict)
for v,k,vs in multi:
out[k]={**out[k],**{v:vs[0]}}
Output
defaultdict(dict,
{77766: {14: 2, 15: 1},
88866: {70: 1, 71: 2, 72: 5, 73: 4, 74: 3},
99966: {79: 1, 80: 2}})
EDIT:
Sorting the inner dictionaries.
out={k:dict(sorted(v.items(),key=lambda x:x[1])) for k,v in out.items()}
Output:
{77766: {15: 1, 14: 2},
88866: {70: 1, 71: 2, 74: 3, 73: 4, 72: 5},
99966: {79: 1, 80: 2}}
Create nested dictionary from directory
instead of using the assignment operator here:
dict[key] = {x[:-4]: {'path': f'database/{x}'}}
call the update
method on the dictionary:
dict[key].update({x[:-4]:{'path': f'database/{x}'}})
Create nested dictionary with same keys from a file
d = {}
for line in file:
line = line.rstrip()
department, name, cre = line.split(',')
if department not in d:
d[department] = {}
d[department][name] = cre
Related Topics
How to Rotate the Sprite and Shoot the Bullets Towards the Mouse Position
How to Edit Header Row in Pandas - Styling
How to Set the R_Home Environment Variable to the R Home Directory
Pyobjc VS Rubycocoa for MAC Development: Which Is More Mature
Output Seckeycopyexternalrepresentation
Ipython Reads Wrong Python Version
Blocking and Non Blocking Subprocess Calls
Efficiently Convert Uneven List of Lists to Minimal Containing Array Padded with Nan
Open File in a Relative Location in Python
Replacing Numpy Elements If Condition Is Met
Pyinstaller Unable to Access Data Folder
Google Fonts (Ttf) Being Ignored in Qtwebengine When Using @Font Face
R's Which() and Which.Min() Equivalent in Python
Restrictons of Python Compared to Ruby: Lambda'S
Swift Playground Error: Module 'Python' Has No Member Named 'Import'
Running an Outside Program (Executable) in Python
Python: Maximum Recursion Depth Exceeded
Python Giving Filenotfounderror for File Name Returned by Os.Listdir