Is there a fast way to truncate the whitespaces in dictionary keys while retaining the dictionary values? Maybe an enumerate or a dictionary comprehensive method.
I am able to do it with .replace(" ", "")
but it created a new list with only the keys and not the values.
Example:
cities = {
"Las Vegas": [36.1215, -115.1739],
"Los Angeles": [34.0500, -118.2500],
"Salt Lake City": [40.7500, -111.8833]
}
to
citiesTruncated = {
"LasVegas": [36.1215, -115.1739],
"LosAngeles": [34.0500, -118.2500],
"SaltLakeCity": [40.7500, -111.8833]
}
A dict-comprehension works:
citiesTruncated = {key.replace(" ", ""): value for key, value in cities.items()}
Note that if you use python2 you should replace the .items()
by .iteritems()
to avoid creating an intermediate list.
Pretty straightforward with a loop or comprehension:
citiesTruncated = {key.replace(' ', ''):value for key,value in cities.items()}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With