A Miraculous Thing

Yesterday, I was pulling out of a parking lot in my 2000 Honda Accord. In front of me was a Honda Civic that looked to be from the late 80's to early 90's. And then, something amazing happened. Our blinkers synchronized! For the half a minute or so we were both waiting for a right turn, our blinkers blinked in unison. Never deviating from the pattern, or moving apart as per usual. I always look at the blinkers at the vain hope that one day, just this will occur. I was so gobsmacked I forgot to memorize the car's plate numbers! It was going the same way as I for a bit, so I followed just behind, and contemplated following the car to its destination but decided against it. After all, what the hell am I going to do? Go up to the driver and introduce myself? Instead, I will just be content in the knowledge that for me, there is a car out there that blinks just like mine.

Merging Dictionaries and Lists in Python

Edit:

Apparently this got posted to reddit a while ago, and several better versions were provided, here's what I would use now:

 def merge_lists(*ls): return sum(ls, [])
 def merge_dicts(*dicts): dict(merge_lists(*map(dict.items, dicts))) 


I came up with what I think is a rather pretty and elegant way to merge dictionaries (and lists) in Python:

def merge_lists(*lists):
 return reduce(lambda x, y: x+y,lists)

def merge_dicts(*dictionaries):
 result = {}
 
 for key in set(merge_lists([d.keys() for d in dictionaries])):
 result[key] = merge_lists([d[key] for d in dictionaries if key in d])
 
 return result 

Some explanation for novices:

  • The *arg notation means that any unnamed arguments (that is, not like this: funct(foo="bar")) will be stores in a tuple named arg.
  • The reduce(funct,collection) will sequentially apply the function funct() to each member of collection. The classic example is that reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5).
  • List comperehensions are super fun and work like this: [something(value) for value in list] does something to each value in list, and returns the results in a list containing the results of something(value). There is a permutation that looks like this: [something(value) for value in list if value > 5] (any condition can be placed after the if), this only adds something(value) to the list if the condition is true.