Index dictionaries inside a list [duplicate] - python

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

Related

Python - Converting list to dict pairwise [duplicate]

This question already has answers here:
Iterating over every two elements in a list [duplicate]
(22 answers)
Closed 4 years ago.
I have a list that looks like this:
mylist = [1, 'a', 2, 'b', 3, 'c']
and would like to end up with a dictionary:
mydict = {
'a': 1,
'b': 2,
'c': 3,}
At the moment I'm achieving it like so:
mydict = {}
for i, k in enumerate(mylist):
if i == len(mylist)/2:
break
v = 2 * i
mydict[mylist[v+1]] = mylist[v]
Is there a more pythonic way of achieving the same thing? I looked up the itertools reference but didn't find anything in particular that would help with the above.
Note: I'm happy with what I have in terms of achieving the goal, but am curious if there is anything that would be more commonly used in such a situation.
Try this
# keys
k = mylist[1::2]
# values
v = mylist[::2]
# dictionary
mydict = dict(zip(k, v))

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

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}}

how to convert a list of dictionary to one dicarionary [duplicate]

This question already has answers here:
How do I merge a list of dicts into a single dict?
(11 answers)
Closed 5 years ago.
Right now i have this:
A={0:[{1:2},{2:3}],
1:[{4:5},{5:6}]}
And I want to change this dictionary to the following:
A={0:{1:2,2:3},
1:{4:5,5:6}}
Is this possible?
Try doing this: Iterate over the elements int the list and merge them into temp_dict. assign temp_dict to the key of the original dictionary.
A={0:[{1:2},{2:3}],
1:[{4:5},{5:6}]}
for k,v in A.items():
temp_dict={}
for elem in v:
for k2,v2 in elem.items():
temp_dict[k2] = v2
A[k] = temp_dict
print A
# prints {0: {1: 2, 2: 3}, 1: {4: 5, 5: 6}}

Python - add key-value pair to dictionary in array [duplicate]

This question already has answers here:
List of lists changes reflected across sublists unexpectedly
(17 answers)
Closed 7 years ago.
Question is in title. I can't make it work:
>>> data = [{}] * 2
>>> data[1].update({3:4})
>>> data
[{3: 4}, {3: 4}]
key-value pair adds to all elements of array. I expected to receive that:
[{}, {3: 4}]
The problem is that
data = [{}] * 2
Creates a list that has the same dictionary in it twice.
To illustrate this, let's look at id(data[0]) and id(data[1]):
>>> data = [{}] * 2
>>> data
[{}, {}]
>>> id(data[0])
4490760552
>>> id(data[1])
4490760552
Note that id(data[0]) and id(data[1]) are the same because both entries in the list refer to the same object
What you probably want is
>>> d2 = [{} for i in range(2)]
>>> d2[0][4] = 'a'
>>> d2
[{4: 'a'}, {}]
Instead of using:
data = [{}] * 2
data[1].update({3:4})
print data
which adds the same dictionary to your list, use this instead:
data = [{}, {}]
data[1].update({3:4})
print data
data[1] now means the second {} in your list. The result of this program is:
[{}, {3: 4}]
Why doesn't data = [{}] * 2 work? Because it you are making the same thing twice, which means you are forced to replace both {} with {3:4} which gives you the result you had. With data = [{}, {}], you can only change the second dictionary since data[0] is the first one and data[1] is the next item and so on.
The problem is, that you added the same dictionary twice to your list.
The trouble is already in your first statement:
data = [{}] * 2
This creates a list with two times the same entry. When you update one of those, the update will be visible in both entries of the list.
Try this:
data = [ {} for i in range(2) ]
When you now do your update, you will get your expected result.

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