Got bitten by Python’s default parameters?

Python’s default parameters are very convenient to use. Python programmers usually get bitten (once) with the fact that in Python functions are first-class objects and default parameters are kind of “member data”. So this would happen:


def foo(a=[]):
    a.append(5)
    return a
>>> foo()
[5]
>>> foo()
[5, 5]
>>> foo()
[5, 5, 5]
>>> foo()
[5, 5, 5, 5]

The detailed explanation of why this is happening could be found here and here.

But just keep in mind that the best way to not fall in to it, would be:

def myfunc(value=None):
    if value is None:
        value = []

Merging Python List of Dictionaries based on specific key

This post is completely based on a cool post on StackOverflow.

So this is the situation, you have two list which they have dictionaries in and you want to merge the dictionaries if they have the same value for one specific field.


x = [{'id':2 , 'name': 'majid'} , {'id':3 , 'name':'maral'}]
y = [{'id':2 , 'num': 22} , {'id':3 , 'num': 33}]

And you want to get the final result like this :

[{'num': 22, 'id': 2, 'name': 'majid'}, {'num': 33, 'id': 3, 'name': 'maral'}]

The function which does the job is as follow (Written by Adam in StackOverflow) :

def merge_lists(l1, l2, key):
  merged = {}
  for item in l1+l2:
    if item[key] in merged:
      merged[item[key]].update(item)
    else:
      merged[item[key]] = item
  return [val for (_, val) in merged.items()]

Now you can test it easily :

merge_lists(x, y , 'id')

Python itertools; Cyclling through a list

 

If you want to loop through a list in Python, and everytime you hit the last one you loop back and start from the beginning without throwing an exception you can use the Cycle module:


>>> <strong>from itertools import cycle</strong>
>>> my_list = [1,2,3]
>>> <strong>my_cycle = cycle(my_list)</strong>
>>> my_cycle.next()
1
>>> my_cycle.next()
2
>>> my_cycle.next()
3
>>> my_cycle.next()
1
>>> my_cycle.next()
2
>>> my_cycle.next()
3
>>> my_cycle.next()
1