List on python appending always the same value
A simplified example of your code currently to explain more fully why your results are the way they are:
all_items = []
new_item = {}
for i in range(0,5):
new_item['a'] = i
new_item['b'] = i
all_items.append(new_item)
print new_item
print hex(id(new_item)) # print memory address of new_item
print all_items
Notice the memory address for your object is the same each time you go through your loop. This means that your object being added is the same, each time. So when you print the final list, you are printing the coordinates of the same object at every location in the loop.
Each time you go through the loop, the values are being updated - imagine you are painting over the same wall every day. The first day, it might be blue. The next day, you repaint the same wall (or object) and then it's green. The last day you paint it orange and it's orange - the same wall is always orange now. Your references to the attr
object are like saying you have the same wall.
Even though you looked at the wall after painting it, the color changed. But afterwards it is a orange wall - even if you look at it 5 times.
When we make the object as a new object in each iteration, notice two things happen:
- the memory address changes
- the values persist as unique values
This is similar to painting different walls. After you finish painting the last one, each of the previous walls is still painted the color you first painted it.
You can see this in the following, where each object is created each iteration:
all_items = []
for i in range(0,5):
new_item = {}
new_item['a'] = i
new_item['b'] = i
all_items.append(new_item)
print hex(id(new_item))
print all_items
You can also do in a different way, such as:
all_items = []
for i in range(0,5):
new_item = {'a': i, 'b': i}
all_items.append(new_item)
print hex(id(new_item))
print all_items
or even in one step:
all_items = []
for i in range(0,5):
all_items.append({'a': i, 'b': i})
print all_items
Either of the following will therefore work:
attr = {}
attr['height'] = height
attr['weight'] = weight
men.append(attr)
or:
men.append({'height': height, 'weight': weight})
Append the same value multiple times to a list
To add v, n times, to l:
l += n * [v]
All elements have same value after appending new element
You're adding the data using the same starting user_info
dict. Move the line you create it inside the for loop.
list append replaces previously appended value
Define the dictionary in the for loop. You are currently writing to same dictionary object, and list holds reference to this object which itself is a reference. As a result you keep modifying the same object.
MyItems = ["ChromeSetup.exe","firefox.exe"]
listofitems = [{"appId": "ChromeID", 'id': "0","name": 'ChromeSetup.exe','_id': 'ChromeUnique'},{"appId": "FireFoxID", 'id': "0","name": 'firefox.exe','_id': 'FireFoxUnique'} ]
__id = ""
appId = ""
result = []
for app in MyItems:
for items in listofitems:
if items['name'] == app:
# I would try to find a better var name.
Dict = {"installerParameters":"","managedApp":{"_id":__id, "appId":appId},"postInstallAction":0,"postInstallScript":{"_id":"0"},"preInstallScript":{"_id":"0"}}
Dict["managedApp"]["_id"] = items['_id']
Dict["managedApp"]["appId"] = items['appId']
print("Dictionery",Dict)
result.append(Dict)
break
print("See the List", result)
Values Duplicate When Appending to List
NOTE - I have only seen the code below num=0
, since I could find duplicates added from that code. Not reviewed code above that.
Change your code from the line where you have num=0
to this :
num = 0
xmin_list = []
ymin_list = []
xmax_list = []
ymax_list = []
for individuals in xy_pairs_list:
if (num % 2) == 0:
xmin = individuals[0]
ymin = individuals[1]
xmin_list.append(int(xmin))
ymin_list.append(int(ymin))
else:
xmax = individuals[0]
ymax = individuals[1]
xmax_list.append(int(xmax))
ymax_list.append(int(ymax))
num = num + 1
print('xmin:', xmin_list, 'ymin:', ymin_list, 'xmax:', xmax_list, 'ymax:', ymax_list)
Python: append an original object vs append a copy of object
This has to do with mutability of the objects you append. If the objects are mutable, they can be updated, and you essentially add a reference to your list with the .append()
function. Thus in these situations you need a copy.
A pretty good list of which types are mutable and not is found on this site. However, generally, container types tend to be mutable whereas simple values typically are immutable.
Appending a dictionary of values to a dictionary of lists with same keys
You can append to a list in this sense like this
dict_v = {'A': 2, 'B': 3, 'C': 4}
dict_l = {'A': [1,3,4], 'B': [8,5,2], 'C': [4,6,2]}
for key in dict_l:
if key in dict_v:
dict_l[key] += [dict_v[key]]
print(dict_l)
The change is that you are appending the value dict_v[key]
as a list [dict_v[key]]
and appending it to the entries that are already in dict_l[key]
using +=
. This way you can also append multiple values as a list to an already existing list.
Related Topics
How to Get First Element in a List of Tuples
Python Sharing a Lock Between Processes
Cmd Opens Windows Store When I Type 'Python'
How to Decode Base64 Data in Python
Matplotlib Scatter Plot Legend
Run Python Script Without Windows Console Appearing
Matplotlib: Save Plot to Numpy Array
How Would I Access Variables from One Class to Another
"Cannot Open Include File: 'Config-Win.H': No Such File or Directory" While Installing MySQL-Python
Pandas - Plotting a Stacked Bar Chart
Python Round Up Integer to Next Hundred
Access Elementtree Node Parent Node
Draw a Transparent Rectangles and Polygons in Pygame
Why Does Assigning to My Global Variables Not Work in Python
Get the Second Largest Number in a List in Linear Time
Windows Is Not Passing Command Line Arguments to Python Programs Executed from the Shell