How to truncate Key Length in Python Dictionary?

PythonProgramming

You can use a list comprehension to truncate keys in a python dict. Iterate over the keys in the dict, and create a new dict with the truncated keys. 

example

def truncate_keys(a, length):
   return dict((k[:length], v) for k, v in a.items())
a = {'foo': 125, 'bar': 'hello'}
b = truncate_keys(a, 2)
print(b)

Output

This will give the output

{'fo': 125, 'ba': 'hello'}

You need to vary about the name collision though. This is because if 2 strings have the same prefix, they will override the values.

raja
Published on 18-Apr-2018 13:02:53
Advertisements