Having some problem adding list values ​in loop - python

My code:
a = {}
b = []
for i in range(1, 5):
a["Name"] = i
print(a)
b.append(a)
print(b)
result is [{'Name': 4}, {'Name': 4}, {'Name': 4}, {'Name': 4}]
how to make [{'Name': 1}, {'Name': 2}, {'Name': 3}, {'Name': 4}]

You are appending the same object over and over. The dictionary a only gets created once. You modify it on each loop iteration, but it's still the same dictionary, so you see the results of the last modification four times.
You want to generate a new dictionary on each loop iteration. Note there is no need to create an empty dictionary and then assign to a key. In this case we can simply use a dictionary literal with thatt key/value pair.
b = []
for i in range(1,5):
a = {'name': i}
print(a)
b.append(a)
print(b)
Or if you don't need print(a) you can do this more concisely with a list comprehension.
b = [{'name': i} for i in range(1, 5)]
print(b)

Just like #njzk2 said, you are modifying the same object.
b = []
for i in range(1, 5):
a = {}
a["Name"] = i
print(a)
b.append(a)
print(b)
This will fix it.
{'Name': 1}
{'Name': 2}
{'Name': 3}
{'Name': 4}
[{'Name': 1}, {'Name': 2}, {'Name': 3}, {'Name': 4}]

Related

why i can't get the result of appending list in python

d={}
for i in range (5):
d['key']=i
lst.append(d)
print(lst)
>>>[{'key': 4}, {'key': 4}, {'key': 4}, {'key': 4}, {'key': 4}]
Why i didn't got this result plz :>>>[{'key': 0}, {'key': 1}, {'key': 2}, {'key': 3}, {'key': 4}] ?
This code will work:
lst = []
for i in range(1, 6):
lst.append({"key", i})
print(lst)
The problem was that you are appending the variable d to lst. the value of lst is now [d, d, d, d, d]. When printing, this evaluates to d's current value, which happens to be {'key', 4}. My code appends the value of d to the list without creating d. This is at least my interpretation of this. Could be wrong.

Comparing key-value from two dictionaries Python

I have this
a = [{'name': 'John', 'supporterId': 1}, {'name': 'Paul', 'supporterId': 2}]
b = [{'dependent': 'Erick','supporterId': 2, 'email': 'erick#gmail.com'}, {'dependent': 'Anna', 'supporterId': 2, 'email': 'ana#gmail.com'}, {'dependent': 'George','supporterId': 13}]
and I need to check if the supporterId between a and b are equal and if so put the name_dependent and email inside the corresponding supporterId in a so for example the output to this should be:
c = [{'name': 'John', 'supporterId': 1}, {'name': 'Paul', 'supporterId': 2, 'data': {'dependent': 'Erick','email': 'erick#gmail.com'},
{'dependent': 'Ana','email':'ana#gmail.com'}]
I have tried many for loops inside another but it doesn't seem to work...
I suggest doing it in a couple of steps. First create a way to look up entries in b by supporterId:
>>> b_supporters = {d['supporterId']: d for d in b}
and then use that to build c:
>>> c = [d | b_supporters.get(d['supporterId'], {}) for d in a]
producing:
>>> c
[{'name': 'John', 'supporterId': 1}, {'name': 'Paul', 'supporterId': 2, 'dependent': 'Anna', 'email': 'ana#gmail.com'}]
I think this solves your problem:
c = []
for i, j in enumerate(a):
c.append(j)
c[i]['data'] = []
for k in b:
if j['supporterId'] == k['supporterId']:
c[i]['data'].append(k)
if not c[i]['data']:
del c[i]['data']
print(c)
Output:
[{'name': 'John', 'supporterId': 1}, {'name': 'Paul', 'supporterId': 2, 'data': [{'dependent': 'Erick', 'supporterId': 2, 'email': 'erick#gmail.com'}, {'dependent': 'Anna', 'supporterId': 2, 'email': 'ana#gmail.com'}]}]

Reuniting two dictionaries with key-value in common

I have two dictionaries and i want to compare them based on the supporterId key like so:
dict1 = [{'name': 'John', 'supporterId': 1}, {'name': 'Paul', 'supporterId': 2}]
dict2 = [{'dependent': 'Erick','supporterId': 2}, {'dependent': 'Anna', 'email': 'anna#gmail.com', 'supporterId': 2}, {'dependent': 'George','email': 'george#gmail.com',supporterId': 13}]
and I need to check if the supporterId between dict1 and dict2 are equal and if so put the name_dependent inside the corresponding supporterId in a so for example the output to this should be:
dict3 = {'name': 'Paul', 'supporterId': 2, 'dependent_name': ['George', 'Anna'], dependent_email: ['anna#gmail.com', 'george#gmail.com']}]

python efficient group by

I am looking for the most efficient way to extract items from a list of dictionaries.I have a list of about 5k dictionaries. I need to extract those records/items for which grouping by a particular field gives more than a threshold T number of records. For example, if T = 2 and dictionary key 'id':
list = [{'name': 'abc', 'id' : 1}, {'name': 'bc', 'id' : 1}, {'name': 'c', 'id' : 1}, {'name': 'bbc', 'id' : 2}]
The result should be:
list = [{'name': 'abc', 'id' : 1}, {'name': 'bc', 'id' : 1}, {'name': 'c', 'id' : 1}]
i.e. All the records with some id such that there are atleast 3 records of same id.
l = [{'name': 'abc', 'id' : 1}, {'name': 'bc', 'id' : 1}, {'name': 'c', 'id' : 1}, {'name': 'bbc', 'id' : 2}]
from collections import defaultdict
from itertools import chain
d = defaultdict(list)
T = 2
for dct in l:
d[dct["id"]].append(dct)
print(list(chain.from_iterable(v for v in d.values() if len(v) > T)))
[{'name': 'abc', 'id': 1}, {'name': 'bc', 'id': 1}, {'name': 'c', 'id': 1}]
If you want to keep them in groups don't chain just use each value:
[v for v in d.values() if len(v) > T] # itervalues for python2
[[{'name': 'abc', 'id': 1}, {'name': 'bc', 'id': 1}, {'name': 'c', 'id': 1}]]
Avoid using list as a variable as it shadows the python list type and if you had a variable list then the code above would cause you a few problems in relation to d = defaultdict(list)
to start out I would make a dictionary to group by your id
control = {}
for d in list:
control.setdefault(d['id'],[]).append(d)
from here all you have to do is check the length of control to see if its greater than your specified threshold
put it in a function like so
def find_by_id(obj, threshold):
control = {}
for d in obj:
control.setdefault(d['id'], []).append(d)
for val in control.values():
if len(val) > threshold:
print val

Finding Index in string with recurring chars

I have string a='51545'
I am finding index of the each char in the string like this
modchar=[{i:a.index(i)} for i in a ]
#modchar=[{'5': 0}, {'1': 1}, {'5': 0}, {'4': 3}, {'5': 0}]
but i need to get it as
#modchar=[{'5': 0}, {'1': 1}, {'5': 2}, {'4': 3}, {'5': 4}]
How can we achieve this?
In this case, you probably want to enumerate the string creating the dictionaries as you go:
[{c: i} for i, c in enumerate(a)]
Note that as a side bonus, this happens in O(n) time opposed to your original solution which is O(n^2)
Try this:
a='51545'
obj = []
for i in range(len(a)):
obj.append({a[i]: i})
This runs as:
>>> a='51545'
>>> obj = []
>>> for i in range(len(a)):
... obj.append({a[i]: i})
...
>>> obj
[{'5': 0}, {'1': 1}, {'5': 2}, {'4': 3}, {'5': 4}]
>>>
You can do list comprehension using enumerate:
[{value: index} for value, index in enumerate(a)]
Which runs as:
>>> [{value: index} for index, value in enumerate(a)]
[{'5': 0}, {'1': 1}, {'5': 2}, {'4': 3}, {'5': 4}]
>>>
Or, you can use a basic list comprehension:
[{a[index]: index} for index in range(len(a))]
Which runs as:
>>> [{a[index]: index} for index in range(len(a))]
[{'5': 0}, {'1': 1}, {'5': 2}, {'4': 3}, {'5': 4}]
>>>
enumerate is basically a combination of using a for loop to get the index, and then accessing the list:
>>> arr = [5, 8, 2, 4]
>>> for index, value in enumerate(arr):
... print index, value
...
0 5
1 8
2 2
3 4
>>>

Categories