Map usage mismatch in python
I have a constants file constants.py
, for example:
querystring = {
"limit":"10000",
"sort":"desc"
}
dummy1 = {
"a": "22",
"q": "*",
}
dummy2 = {
"a": "24",
"q": "**",
}
streams = [dummy1, dummy2]
I am trying to initialize a list by manipulating values ββfrom a file constants.py
.
from constants import querystring, streams
def setParams(dummy, querystring):
ld = {}
ld["query"] = setQuerystring( dummy, querystring)
print ld
return ld
def setQuerystring( dummy, querystring):
query = querystring
query["filter"] = "stream:" + dummy["a"]
query["query"] = dummy["q"]
return query
l = map(lambda x: setParams(x, querystring), streams)
print l[0]
print l[1]
As long as the lambda function is running, the output prints correctly, but when I see the final value returned by the map, the values ββare different. Why is this inconsistency?
Program output:
{'query': {'sort': 'desc', 'filter': 'stream:22', 'limit': '10000', 'query': '*'}} # l[0] -> during lambda execution
{'query': {'sort': 'desc', 'filter': 'stream:24', 'limit': '10000', 'query': '**'}} # l[1] -> during lambda execution
{'query': {'sort': 'desc', 'filter': 'stream:24', 'limit': '10000', 'query': '**'}} # l[0] -> from map
{'query': {'sort': 'desc', 'filter': 'stream:24', 'limit': '10000', 'query': '**'}} # l[1] -> from map
+3
source to share
1 answer
You are reusing and modifying the querystring
dict through iterations. Subsequent changes from successive iterations are then propagated to the previously attached copies. You should consider binding a copy to each dict instead and changing that copy:
def setQuerystring( dummy, querystring):
query = querystring.copy()
...
{'query': {'sort': 'desc', 'filter': 'stream:22', 'limit': '10000', 'query': '*'}}
{'query': {'sort': 'desc', 'filter': 'stream:24', 'limit': '10000', 'query': '**'}}
{'query': {'sort': 'desc', 'filter': 'stream:22', 'limit': '10000', 'query': '*'}}
{'query': {'sort': 'desc', 'filter': 'stream:24', 'limit': '10000', 'query': '**'}}
+3
source to share