For instance,
if dict['sample']:
//append values to dict['sample']
else:
// assign new key to the python dictionary
If dict[‘sample’] is empty, Python will throw errors. Does anyone know a better way to check on this?
All I want is something like that, I will have list of data, let’s say a,a,b,c,g,g,g,g,g.
So, I want python dictionary to append the values of two a,a to dict[‘a’], and g,g,g,g,g to dict[‘g’] and so the rest as dict[‘b’] etc. A for loop will be executed to loop through the data of a,a,b,c,g,g,g,g,g.
I hope I’ve made my question clear. Any idea? Preferably, if Python’s dictionary has a way to check existing key.
EDIT
Credit goes to @Paul McGuire. I’ve figured out the exact solution I wanted based on @Paul McGuire’s answer. As shown below:
from collections import defaultdict
class Test:
def __init__(self, a,b):
self.a=a
self.b=b
data = []
data.append(Test(a=4,b=6))
data.append(Test(a=1,b=2))
data.append(Test(a=1,b=3))
data.append(Test(a=2,b=2))
data.append(Test(a=3,b=2))
data.append(Test(a=4,b=5))
data.append(Test(a=4,b=2))
data.append(Test(a=1,b=2))
data.append(Test(a=5,b=9))
data.append(Test(a=4,b=7))
dd = defaultdict(list)
for c in data:
dd[c.a].append(c.b)
print dd
The old approaches of “if key in dict” or “dict.get” or “dict.setdefault” should all be set aside in favor of the now standard
defaultdict:defaultdict takes care of the checking for key existence for you, all your code has to do is 1) define a factory function or class for the defaultdict to use to initialize a new key entry (in this case,
defaultdict(list)), and 2) define what to do with each key (dd[c].append(c)). Clean, simple, no clutter.In your particular example, you could actually use
itertools.groupby, since the groups of letters are all contiguous for each grouping value.groupbyreturns an iterator of tuples, each tuple containing the current key value and an iterator of the matching values. The following code works by converting each tuple’s list-of-values-iterator to an actual list (inlist(v)), and passing the sequence of key-valuelist tuples to the dict constructor.prints: