How to append multiple lists to a nested dictionary? [duplicate] - python

This question already has answers here:
How to Create Nested Dictionary in Python with 3 lists
(7 answers)
Closed 4 years ago.
Suppose I have three lists:
list_a = [1,2,3]
list_b = ['a','b','c']
list_c = [4,5,6]
How do I create a nested dictionary that looks like this:
dict = {1:{'a':4},2:{'b':5},3:{'c':6}
I was thinking of using the defaultdict command from the collections module or creating a class but I don't know how to do that

You can utilize zip and dictionary comprehension to solve this:
list_a = [1,2,3]
list_b = ['a','b','c']
list_c = [4,5,6]
final_dict = {a:{b:c} for a, b, c in zip(list_a, list_b, list_c)}
Output:
{1: {'a': 4}, 2: {'b': 5}, 3: {'c': 6}}

Related

python flatten/unwrap list of dictionaries in list

I have list of dictionaries in list like below
A = [[{'a': '1', 'b': '2'}],[{...}],[{...}],[],[],[{'x': '25', 'z':'26'}]]
7 lists of dictionaries inside a list "A" (data from 7days)
python using for loop in def function
some lists of dictionaries inside A has data, some doesn't
I want to flatten/unwrap like this into a different list B
B = [{'a': '1', 'b': '2', ..., 'x': '25', 'z':'26'}]
as a list of dictionaries.
I have tried(with corresponding imports):
B = (list(itertools.chain(*A)))
B = [item for sublist in A for item in sublist]
B = [dict(chain(*map(dict.items, d.values()))) for d in A]
Above 3 flattening/unwrapping methods give me an empty list [] as a result.
I want to do this because just one list will fit to my ajax append format in html
that will be applied for data sets for month, quarter, half-year, and year as well.(I also need to flatten 365 lists of dictionaries in a list with for loop is used to create this list)
Am I using above method wrong?
Does flattening/unwrapping has to follow the each unorganized list of lists' structure?
Is it better not to create the unorganized list like list A by changing for loop from python using for loop in def function ?
EDIT: I separated unflatten list(A) and flatten list(B) in the question.
You can use itertools.chain() and dict comprehension:
A = [[{1:1, 2:2}], [], [{3:3}], [{8:8}], [], [], [{9:9}]]
b = itertools.chain(*A)
{k:v for x in b for k,v in x.items()}
Expected result:
{1: 1, 2: 2, 3: 3, 8: 8, 9: 9}
More about itertools: https://www.geeksforgeeks.org/python-itertools/
More about dict comprehension: https://www.programiz.com/python-programming/dictionary-comprehension

How to create a list of dicts into a single dict with python? [duplicate]

This question already has answers here:
How do I merge a list of dicts into a single dict?
(11 answers)
How do I merge dictionaries together in Python?
(7 answers)
Closed 1 year ago.
I have a large list of dictionaries, each with exactly one entry and with unique keys, and I want to 'combine' them into a single dict with python 3.8.
So here is an example that actually works:
mylist = [{'a':1}, {'b':2}, {'c':3}]
mydict = {list(x.keys())[0]:list(x.values())[0] for x in mylist}
which gives as result the expected output:
{'a': 1, 'b': 2, 'c': 3}
But it looks ugly and not quite pythonic. Is there a better one-line solution to this problem?
This is similar to the question asked HERE, but in my example I am looking for an answer (1) to merge many dicts together and (2) for a one-line solution. That makes my question different from the question already asked.
mydict = { k:v for elt in mylist for k, v in elt.items()}
Try this out, simple and effective.
mylist = [{'a':1}, {'b':2}, {'c':3}]
result = {}
for d in mylist:
result.update(d)
Result
{'a': 1, 'b': 2, 'c': 3}

Index dictionaries inside a list [duplicate]

This question already has answers here:
List of lists changes reflected across sublists unexpectedly
(17 answers)
Create list of single item repeated N times
(9 answers)
Closed 5 years ago.
I have a list of dictionaries:
dicty = [defaultdict(list)] * (2)
dicty
[defaultdict(list, {}), defaultdict(list, {})]
Now I want to know how to index into these dictionaries?
I have tried:
dicty[0][0].append('abc')
dicty
[defaultdict(list, {0: ['abc']}), defaultdict(list, {0: ['abc']})]
But as you can see that it appends in both the dictionaries. I want to learn how to append into an individual dictionary.
You can use:
dicty = [defaultdict(list) for _ in range(2)]
When using [defaultdict(list)] * (2), all your dicts point to the same object in memory.
from collections import defaultdict
""" Here, you are saying that you wish to add twice "defaultdict(list)".
These are the same objects. You are just duplicating the same one with *
"""
dicty = [defaultdict(list)] * (2)
dicty[0][0].append('abc')
print dicty
print dicty[0] is dicty[1], '\n'
""" However, here : you are creating two distinct dictionnaries.
"""
dicty = []
for _ in range(2):
dicty.append(defaultdict(list))
dicty[0][0].append('abc')
print dicty
print dicty[0] is dicty[1]
# outputs :
#[defaultdict(<type 'list'>, {0: ['abc']}), defaultdict(<type 'list'>, {0: ['abc']})]
#True
#[defaultdict(<type 'list'>, {0: ['abc']}), defaultdict(<type 'list'>, {})]
#False

recursive itemgetter for python [duplicate]

This question already has answers here:
Access nested dictionary items via a list of keys?
(20 answers)
Xpath like query for nested python dictionaries
(11 answers)
Closed 6 years ago.
Is there a recursive itemgetter in python. Let's say you have an object like
d = {'a': (1,2,3), 'b': {1: (5,6)}}
and I wanted to get the first element of the tuple from d['a']? As far as I can tell itemgetter will only do one level, i.e. get me a or b or both.
Is there some clever way of combining itertools with itemgetter to produce the desired result.
So basically what I want to be able to call is
from operator import itemgetter
d = {'a': (1,2), 'b': (4, (5,))}
itemgetter({'a': 0})(d) --> 1
itemgetter({'b': 0})(d) --> 4
itemgetter({'b': {1: 0}})(d) --> 5
d = {'a': {'b': (1,2,3)}}
itemgetter({'a': {'b': 2}})(d) --> 3
I don't like 'clever' ways. Obvious is better.
You can very easily write a getter that iterates along a list of subscripts:
def getter(x, *args):
for k in args:
x = x[k]
return x
>>> d = {'a': (1,2,3), 'b': {1: (5,6)}}
>>> getter(d, 'a', 0)
1

syntax for creating a dictionary into another dictionary in python [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
syntax to insert one list into another list in python
How could be the syntax for creating a dictionary into another dictionary in python
You can declare a dictionary inside a dictionary by nesting the {} containers:
d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}
And then you can access the elements using the [] syntax:
print d['dict1'] # {'foo': 1, 'bar': 2}
print d['dict1']['foo'] # 1
print d['dict2']['quux'] # 4
Given the above, if you want to add another dictionary to the dictionary, it can be done like so:
d['dict3'] = {'spam': 5, 'ham': 6}
or if you prefer to add items to the internal dictionary one by one:
d['dict4'] = {}
d['dict4']['king'] = 7
d['dict4']['queen'] = 8
dict1 = {}
dict1['dict2'] = {}
print dict1
>>> {'dict2': {},}
this is commonly known as nesting iterators into other iterators I think
Do you want to insert one dictionary into the other, as one of its elements, or do you want to reference the values of one dictionary from the keys of another?
Previous answers have already covered the first case, where you are creating a dictionary within another dictionary.
To re-reference the values of one dictionary into another, you can use dict.update:
>>> d1 = {1: [1]}
>>> d2 = {2: [2]}
>>> d1.update(d2)
>>> d1
{1: [1], 2: [2]}
A change to a value that's present in both dictionaries will be visible in both:
>>> d1[2].append('appended')
>>> d1
{1: [1], 2: [2, 'appended']}
>>> d2
{2: [2, 'appended']}
This is the same as copying the value over or making a new dictionary with it, i.e.
>>> d3 = {1: d1[1]}
>>> d3[1].append('appended from d3')
>>> d1[1]
[1, 'appended from d3']

Categories

Resources