Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to combine substrings in dictionary keys

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]
}
like image 545
pyrochan157 Avatar asked Feb 09 '23 04:02

pyrochan157


2 Answers

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.

like image 139
David Zwicker Avatar answered Feb 12 '23 10:02

David Zwicker


Pretty straightforward with a loop or comprehension:

citiesTruncated = {key.replace(' ', ''):value for key,value in cities.items()}
like image 38
TigerhawkT3 Avatar answered Feb 12 '23 10:02

TigerhawkT3