How to truncate Key Length in Python Dictionary?


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.

Updated on: 05-Mar-2020

397 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements