Why does the list not save the elements? - python

while(True):
size,times = map(int,input().split())
v=list(map(int,input().split()))
store=dict()
for i in range(size):
store[v[i]]=list()
store[v[i]].append(i+1)
print(store)
while(times>0):
pos,num = map(int,input().split())
For example:
size=8 (input array size) times=4
pos=1 (The position of num in list start by 1) num=3
{1: [1]}
{1: [1], 3: [2]}
{1: [1], 3: [2], 2: [3]}
{1: [1], 3: [2], 2: [4]}
{1: [1], 3: [2], 2: [4], 4: [5]}
{1: [1], 3: [6], 2: [4], 4: [5]}
{1: [1], 3: [6], 2: [7], 4: [5]}
{1: [8], 3: [6], 2: [7], 4: [5]}
Things I want:
{1: [1]}
{1: [1], 3: [2]}
{1: [1], 3: [2], 2: [3]}
{1: [1], 3: [2], 2: [3,4]}
{1: [1], 3: [2], 2: [3,4], 4: [5]}
{1: [1], 3: [2,6], 2: [4], 4: [5]}
{1: [1], 3: [2,6], 2: [3,4,7], 4: [5]}
{1: [1,8], 3: [2,6], 2: [3,4,7], 4: [5]}

This line store[v[i]]=list() is creating a new list every time
remove it and change the next append line to:
store.setdefault(v[i], list()).append(i+1)
That will create the list only if it doesn't exist.
Alternatively use collections.defaultdict(list)

Related

how can I add an element to a nested dictionary [duplicate]

This question already has answers here:
How do I initialize a dictionary of empty lists in Python?
(7 answers)
Closed last month.
here's my code:
import copy
teamdict = {1:{},2:{},3:{},4:{},5:{}}
teamlst = []
matchlst = [1,2,3,4,5]
lst = [[1,5,0],[1,0,3],[2,3,0],[2,0,1],[3,0,6],[3,0,1],[4,0,1],[4,0,5],[5,0,8]]
for i in matchlst:
for j in lst:
if i == j[0]:
teamlst.append(j[2])
elif len(teamlst)>0 and i != j:
continue
else:
pass
teamlst = set(teamlst)
teamlst = list(teamlst)
teamlst.sort()
team_dictionary = dict.fromkeys(teamlst, [])
teamdict[i] = team_dictionary
teamlst.clear()
print(teamdict)
dic = copy.deepcopy(teamdict)
for i in lst:
dic[i[0]][i[2]].append(i[1])
print(dic)
this is what i got:
{1: {0: [5, 0], 3: [5, 0]}, 2: {0: [3, 0], 1: [3, 0]}, 3: {1: [0, 0], 6: [0, 0]}, 4: {1: [0, 0], 5: [0, 0]}, 5: {8: [0]}}
but what i expect is:
{1: {0: [5], 3: [0]}, 2: {0: [3], 1: [0]}, 3: {1: [0], 6: [0]}, 4: {1: [0], 5: [0]}, 5: {8: [0]}}
what goes wrong?
seems like this append method add the element to all the keys in the nested dictionary
I assume you have created your dictionary with multiple references to the same list.
If I execute your code I get what you want.
>>> lst = [[1,5,0],[1,0,3],[2,3,0],[2,0,1],[3,0,6],[3,0,1],[4,0,1],[4,0,5],[5,0,8]]
>>> dic = {1: {0: [], 3: []}, 2: {0: [], 1: []}, 3: {1: [], 6: []}, 4: {1: [], 5: []}, 5: {8: []}}
>>> for i in lst:
... dic[i[0]][i[2]].append(i[1])
...
>>> print(dic)
{1: {0: [5], 3: [0]}, 2: {0: [3], 1: [0]}, 3: {1: [0], 6: [0]}, 4: {1: [0], 5: [0]}, 5: {8: [0]}}

Python: how to converet list of list into a dictionary

I am trying to converet the list of list into a dictionary using defaultdict method.
I have a list of list:
a= [[1,2],[2,3,4], [4,5,6], [3,7], [6,10]]
I want the output in this format:
{1: [0], 2: [0], 2: [1], 3: [1], 4: [1], 4: [2], 5: [2], 6: [2], 3: [3], 7: [3], 6: [4], 10: [4]})
Here is my code:
a =[[1,2],[2,3,4], [4,5,6], [3,7], [6,10]]
clusters = defaultdict(list)
cluster_sz = {}
cliques = []
cluster_idx = 0
for clique in a:
cliques.append(clique)
for v in clique:
clusters[v].append(cluster_idx)
cluster_idx+=1
print(clusters)
The output of this code is:
{1: [0], 2: [0,1], 3: [1,3], 4: [1, 2], 5: [2], 6: [2, 4], 7: [3], 10: [4]})
But I need this type of output:
{1: [0], 2: [0], 2: [1], 3: [1], 4: [1], 4: [2], 5: [2], 6: [2], 3: [3], 7: [3], 6: [4], 10: [4]})
You can try with this approach
So instead of dictionary with overlapping keys, you can create list of dictionaries.
a= [[1,2],[2,3,4], [4,5,6], [3,7], [6,10]]
b = [{r:i} for i,k in enumerate(a) for r in k ]
[{1: 0}, {2: 0}, {2: 1}, {3: 1}, {4: 1}, {4: 2}, {5: 2}, {6: 2}, {3: 3}, {7: 3}, {6: 4}, {10: 4}]
Here is a shortened code with your desired output.
a = [[1,2],[2,3,4], [4,5,6], [3,7], [6,10]]
d = {}
for i, sublist in enumerate(a):
for num in sublist:
if num not in d:
d[num] = []
d[num].append(i)
print(d)
dict = {1: [0], 2: [0,1], 3: [1,3], 4: [1, 2], 5: [2], 6: [2, 4], 7: [3], 10: [4]}
convertedDict = {}
for (i, j) in dict.items():
if len(j) > 1:
for k in j:
convertedDict[i] = [k]
else:
convertedDict[i] = j
print (convertedDict)
{1: [0], 2: [1], 3: [3], 4: [2], 5: [2], 6: [4], 7: [3], 10: [4]}
Those object, have duplicated keys, thats the reason, why, converted dict saving only last value in last iteration.
https://thispointer.com/can-a-dictionary-have-duplicate-keys-in-python/

Combine two dictionaries based on value of 1st and key of 2nd

I have the following two dictionaries:
{1: ['1'], 2: ['1'], 3: ['1'], 4: ['2'], 5: ['1']}
{1: ['2|N|'], 2: ['1|N|']}
I want to take the key of dictionary 2 and link it with the value's of dictionary 1, for a desired output of the following:
{1: ['2|N|'], 2: ['2|N|'], 3: ['2|N|'], 4: ['1|N|'], 5: ['2|N|']}
Basically combining the key, value of dictionary 2 on the value of dictionary 1.
Pretty straightforward solution:
adict = {1: ['1'], 2: ['1'], 3: ['1'], 4: ['2'], 5: ['1']}
mapping = {1: ['2|N|'], 2: ['1|N|']}
for key, value in adict.items():
adict[key] = [mapping[int(k)][0] for k in value]
print(adict)
Output:
{1: ['2|N|'], 2: ['2|N|'], 3: ['2|N|'], 4: ['1|N|'], 5: ['2|N|']}
here is dict comprehension manner of it
{k:b[int(v[0])] for k,v in a.items() }
{1: ['2|N|'], 2: ['2|N|'], 3: ['2|N|'], 4: ['1|N|'], 5: ['2|N|']}

Python Dictionary: Accessing the previous value using current/present key

I want to be able to use a 'present' key and generate it's previous key's values. Here is an example with a starting point from which I am unable to move further:
#d= {}
d = {
{'Neighbour_values': [{3: [2, 89.5488]}, {3: [4, 23.0558]}, {4: [2, 89.5488]}, {5: [2, 89.5488]}, {5: [3, 122.153]}, {5: [4, 22.9872]}, {6: [2, 89.5488]}, {6: [4, 22.9872]}, {7: [2, 89.5488]}, {7: [4, 22.9872]}, {8: [3, 122.153]}, {8: [4, 22.9872]}]},
{'Neighbour_values': [{3: [4, 23.0558]}, {4: [1, 19.9884]}, {4: [3, 122.153]}, {5: [1, 19.9884]}, {6: [1, 19.9884]}, {6: [3, 122.153]}, {7: [1, 19.9884]}, {8: [1, 19.9884]}, {8: [3, 122.153]}]},
{'Neighbour_values': [{3: [2, 89.5488]}, {3: [4, 23.0558]}, {3: [6, 20.4196]}, {4: [1, 19.9884]}, {4: [2, 89.5488]}, {5: [1, 19.9884]}, {5: [4, 22.9872]}, {6: [2, 89.5488]}, {6: [4, 22.9872]}, {7: [2, 89.5488]}, {7: [4, 22.9872]}, {8: [2, 89.5488]}]},
{'Neighbour_values': [{3: [1, 122.153]}, {3: [3, 71.1785]}, {3: [6, 20.4196]}, {4: [6, 20.4196]}, {5: [1, 19.9884]}, {6: [1, 19.9884]}, {6: [3, 122.153]}, {6: [6, 20.4196]}, {7: [1, 19.9884]}, {7: [6, 19.9002]}, {8: [1, 19.9884]}, {8: [3, 122.153]}]},
{'Neighbour_values': [{3: [4, 23.0558]}, {4: [4, 23.0362]}, {6: [3, 122.153]}, {6: [4, 22.9872]}, {7: [4, 22.9872]}, {8: [3, 122.153]}, {8: [4, 22.9872]}]}
}
#print '\n'
#print(d)
for value in range(3,9):
print '--- value ---'
if value == 4:
print value of 'Neighbour_values' in key 3 i.e 89.5488 and in next line 23.0558 (but do not print 2, 4)
#and continue with the other keys in the dictionary i.e "for 2, 3, 4, and 6"
next if value == 4+2:
continue the above logic by printing value of 'Neighbour_values' in key 5 (again, only the float values and not the integers)
Of course a little bit of Pseudo code is written in the code as I do not know what to do further.
Any help is appreciated. Thanks in advance :)
(Using Ubuntu 14.04 32-Bit VM and Python 2.7)
UPDATE
Edited the dictionary to be more precise as to what I want for in the solution.
Hope this makes the question more clear.
In Python, dictionaries do not have a specific order.
However, you CAN use collections.OrderedDict to preserve the order that keys were inserted.
You can use it like so:
d = {'one': 1, 'two': 2, 'three': 3}
ordered = OrderedDict(d)
and to get the previous key's values, you could do something like this:
def previous_value(dictionary, current_key):
# Get the list of keys from the OrderedDict
keys = list(dictionary.keys())
# Get an index of the current key and offset it by -1
index = keys.index(current_key) - 1
# return the previous key's value
return dictionary[keys[index]]
Testing it:
print('value before "three": {}'.format(previous_value(ordered, 'three')))
# prints - value before "three": 2
print('value before "two": {}'.format(previous_value(ordered, 'two')))
# prints - value before "two": 1
Try
print('\n'.join([str(l[value-1][1]) for e in d for l in e[1]['Neighbour_values'] if value-1 in l]))
output
89.5488
23.0558
23.0558
89.5488
23.0558
20.4196
122.153
71.1785
20.4196
23.0558
89.5488
19.9884
122.153
19.9884
89.5488
20.4196
23.0362
89.5488
122.153
22.9872
19.9884
19.9884
22.9872
19.9884
89.5488
22.9872
19.9884
122.153
89.5488
22.9872
19.9884
122.153
20.4196
122.153
22.9872
89.5488
22.9872
19.9884
89.5488
22.9872
19.9884
19.9002
22.9872
Explanation
print('\n'.join( #Separate each element by \n
[ #Start List comprehension
str(l[value-1][1]) #select item 1 from [2, 89.5488]
for e in d #for each main tuple of (1, {'Neighbour_values':...
for l in e[1]['Neighbour_values'] #iterate over dictionary like {3: [2, 89.5488]}
if value-1 in l #select only if key of value-1 is there
]
))
As your keys in this case are int, am not sure if you need to use OrderedDict. But if you are comfortable with your data structure for whatever reason, I'm just posting this as a way to wade through it to achieve your output.
UPDATED for additional detail in OP
Your latest d is not a proper dictionary as it doesn't have keys, so I changed it to a dictionary with keys. If you want the code to work properly please use the d as initialized below:
d = {
1:{'Neighbour_values': [{3: [2, 89.5488]}, {3: [4, 23.0558]}, {4: [2, 89.5488]}, {5: [2, 89.5488]}, {5: [3, 122.153]}, {5: [4, 22.9872]}, {6: [2, 89.5488]}, {6: [4, 22.9872]}, {7: [2, 89.5488]}, {7: [4, 22.9872]}, {8: [3, 122.153]}, {8: [4, 22.9872]}]},
2:{'Neighbour_values': [{3: [4, 23.0558]}, {4: [1, 19.9884]}, {4: [3, 122.153]}, {5: [1, 19.9884]}, {6: [1, 19.9884]}, {6: [3, 122.153]}, {7: [1, 19.9884]}, {8: [1, 19.9884]}, {8: [3, 122.153]}]},
3:{'Neighbour_values': [{3: [2, 89.5488]}, {3: [4, 23.0558]}, {3: [6, 20.4196]}, {4: [1, 19.9884]}, {4: [2, 89.5488]}, {5: [1, 19.9884]}, {5: [4, 22.9872]}, {6: [2, 89.5488]}, {6: [4, 22.9872]}, {7: [2, 89.5488]}, {7: [4, 22.9872]}, {8: [2, 89.5488]}]},
4:{'Neighbour_values': [{3: [1, 122.153]}, {3: [3, 71.1785]}, {3: [6, 20.4196]}, {4: [6, 20.4196]}, {5: [1, 19.9884]}, {6: [1, 19.9884]}, {6: [3, 122.153]}, {6: [6, 20.4196]}, {7: [1, 19.9884]}, {7: [6, 19.9002]}, {8: [1, 19.9884]}, {8: [3, 122.153]}]},
5:{'Neighbour_values': [{3: [4, 23.0558]}, {4: [4, 23.0362]}, {6: [3, 122.153]}, {6: [4, 22.9872]}, {7: [4, 22.9872]}, {8: [3, 122.153]}, {8: [4, 22.9872]}]}
}
for value in range(3,9):
for in_d in d.values():
for in_in_d in in_d['Neighbour_values']:
if value-1 in in_in_d:
print(in_in_d[value-1][1])

Turn Dictionary of Sets into Dictionary of Lists

Given the Dictionary of Sets:
{1: {2}, 2: {1, 3, 5}, 3: {2, 4}, 4: {3, 7}, 5: {2, 6}, 6: {5}, 7: {8, 4}, 8: {7}}
Is there anyway I can easily turn it into a Dictionary of Lists?
Desired Output:
{1: [2], 2: [1, 3, 5], 3: [2, 4], 4: [3, 7], 5: [2, 6], 6: [5], 7: [8, 4], 8: [7]}
result = {key: list(values) for key, values in dictionary.items()}
Use dict comprehension and convert set to list using the list() function
a = {1: {2}, 2: {1, 3, 5}, 3: {2, 4}, 4: {3, 7}, 5: {2, 6}, 6: {5}, 7: {8, 4}, 8: {7}}
{k:list(v) for k,v in a.items()}
Out[274]:
{1: [2],
2: [1, 3, 5],
3: [2, 4],
4: [3, 7],
5: [2, 6],
6: [5],
7: [8, 4],
8: [7]}

Categories

Resources