Object of custom type as dictionary key

You need to add 2 methods, note __hash__ and __eq__: class MyThing: def __init__(self,name,location,length): self.name = name self.location = location self.length = length def __hash__(self): return hash((self.name, self.location)) def __eq__(self, other): return (self.name, self.location) == (other.name, other.location) def __ne__(self, other): # Not strictly necessary, but to avoid having both x==y and x!=y # True at … Read more

How to create a dictionary of two pandas DataFrame columns

In [9]: pd.Series(df.Letter.values,index=df.Position).to_dict() Out[9]: {1: ‘a’, 2: ‘b’, 3: ‘c’, 4: ‘d’, 5: ‘e’} Speed comparion (using Wouter’s method) In [6]: df = pd.DataFrame(randint(0,10,10000).reshape(5000,2),columns=list(‘AB’)) In [7]: %timeit dict(zip(df.A,df.B)) 1000 loops, best of 3: 1.27 ms per loop In [8]: %timeit pd.Series(df.A.values,index=df.B).to_dict() 1000 loops, best of 3: 987 us per loop

List of unique dictionaries

So make a temporary dict with the key being the id. This filters out the duplicates. The values() of the dict will be the list In Python2.7 >>> L=[ … {‘id’:1,’name’:’john’, ‘age’:34}, … {‘id’:1,’name’:’john’, ‘age’:34}, … {‘id’:2,’name’:’hanna’, ‘age’:30}, … ] >>> {v[‘id’]:v for v in L}.values() [{‘age’: 34, ‘id’: 1, ‘name’: ‘john’}, {‘age’: 30, ‘id’: … Read more

Why is it faster to check if dictionary contains the key, rather than catch the exception in case it doesn’t?

On the one hand, throwing exceptions is inherently expensive, because the stack has to be unwound etc. On the other hand, accessing a value in a dictionary by its key is cheap, because it’s a fast, O(1) operation. BTW: The correct way to do this is to use TryGetValue obj item; if(!dict.TryGetValue(name, out item)) return … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)