wordpress meta
title: 'Python Append Key'
date: '2021-12-04T10:02:02-05:00'
status: publish
permalink: /python-append-key
author: admin
excerpt: ''
type: post
id: xxxx
category:
- 'python'
tag: ['python','dict']
post_format: []
title: 'Python Append Key'
date: '2021-12-04T10:02:02-05:00'
status: publish
permalink: /python-append-key
author: admin
excerpt: ''
type: post
id: xxxx
category:
- 'python'
tag: ['python','dict']
post_format: []
Python Append Key
Building a dict and ordering it into groups by key is sometimes very useful.
Teh following code show using the if .. in option and defaultdict option of checkign for a key when loading the dictionary. Although people warn that using has_key or if .. in type checks slows it down a lot my timings was fairly similar. I left some commented code in for my own reference.
source
from collections import defaultdict
from time import time
sample_size = 10000000
dct1 = defaultdict(list)
dct1 = {}
st_time = time()
for i in range(1, sample_size):
s = str(i)
key = s[0:1]
name = 'server' + s
dct1.setdefault(key, []).append({'name':name,'status':'RUNNING'}) # returns None!
print (f"\ndct1 defaultdict option: {time() - st_time}")
#print (dct1)
# get one key
#one_key = dct1.get('2')
#print (one_key)
#for v in one_key:
# print (v)
# print by key
#for k,v in dct1.items():
# print("\nkey == {}".format(k))
# print (v)
# #for i in v:
# # print(" {} {}".format(i["name"], i["status"]))
dct2 = {}
st_time = time()
for i in range(1, sample_size):
s = str(i)
key = s[0:1]
name = 'server' + s
if key in dct2:
dct2[key].append({'name':name,'status': 'STOPPED'})
else:
dct2.update({key: [{'name': name,'status': 'STOPPED'}]})
print (f"\ndct2 if .. in option: {time() - st_time}")
#print (dct2)
#one_key = dct1.get('1')
#print (one_key)
#for v in one_key:
# print (v)
# print by key
#for k,v in dct2.items():
# print("\nkey == {}".format(k))
# print (v)
# #for i in v:
# # print(" {} {}".format(i["name"], i["status"]))
test
py-assoc-arr$ python3 py-keyed-dict-timing.py
dct1 defaultdict option: 6.392352342605591
dct2 if .. in option: 6.472132921218872