
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Advertisements