Problem description

With the append() method of the list, the data at the front is always overwritten by the data at the back

Problem code

def process() :
	proxies = {'180.97.104.97:80': '{" proxy ":" 180.97.104.97:80 "}', \
	'123.125.114.18:80': '{" proxy ":" 123.125.114.18:80 "}', \
	'123.125.115.242:80': '{" proxy ":" 123.125.115.242:80 "}'}

	proxy_dict = {}	Define the dictionary outside the loop
	cnt = 0
	proxy_list = []
	for proxy in proxies:
		print(proxy)
		ip, port = proxy.split(":")
		proxy_dict['ip'] = ip
		proxy_dict['port'] = port
	
		proxy_list.append(proxy_dict)
		cnt += 1

	print('total ip: ', cnt)

	return proxy_list

good_proxy = process()
print(good_proxy)
Copy the code

The execution result

Find that all the data in the list is the last data in the dictionary.

[root@2c9a57af434c test]# python test.py 
total ip:  3
[{'ip': '123.125.115.242'.'port': '80'}, {'ip': '123.125.115.242'.'port': '80'}, {'ip': '123.125.115.242'.'port': '80'}]
Copy the code

The solution

code


```python
def process():
	proxies = {'180.97.104.97:80': '{" proxy ":" 180.97.104.97:80 "}', \
	'123.125.114.18:80': '{" proxy ":" 123.125.114.18:80 "}', \
	'123.125.115.242:80': '{" proxy ":" 123.125.115.242:80 "}'}

	
	cnt = 0
	proxy_list = []
	for proxy in proxies:
		proxy_dict = {} The dictionary is defined inside the loop
		ip, port = proxy.split(":")
		proxy_dict['ip'] = ip
		proxy_dict['port'] = port
	
		proxy_list.append(proxy_dict)
		cnt += 1

	print('total ip: ', cnt)

	return proxy_list

good_proxy = process()
print(good_proxy)
Copy the code

The execution result

Every element in the dictionary is put in the list.

[root@2c9a57af434c test]# python test.py 
total ip:  3
[{'ip': '180.97.104.97'.'port': '80'}, {'ip': '123.125.114.18'.'port': '80'}, {'ip': '123.125.115.242'.'port': '80'}]
Copy the code

explain

Dict defines only one address outside of a loop, and the address stays the same each time through the loop, overwriting the preceding data. This can be understood in terms of shallow copy and deep copy.

Assignments between objects in Python are passed by reference. If you need to copy objects, you need to use the copy module in the standard library.

  • Copy. Shallow copy Copies only the parent object, not the internal child objects of the object.
  • Copy. Deepcopy deepcopy copy objects and their children