The method of combining substrings in dictionary keys

Is there a quick way to trim spaces in dictionary keys by storing dictionary values? Maybe enumerate or a comprehensive method dictionary.

I can do this with .replace(" ", ""), but he created a new list with only keys, not 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]
}
+4
source share
3 answers

Work with the recorder:

citiesTruncated = {key.replace(" ", ""): value for key, value in cities.items()}

Note that if you are using python2, you should replace .items()with .iteritems()to avoid creating an intermediate list.

+4
source

Pretty simple with a loop or understanding:

citiesTruncated = {key.replace(' ', ''):value for key,value in cities.items()}
+4
source

dict, ( dict ). , , - :

for key in cities:
    new_key = key.replace(' ', '')
    if new_key == key:
        continue
    cities[new_key] = d[key]
    del cities[key]

Otherwise, if you do not require or even do not want to preserve your identity ( truncatedCities- this is just created dictand not the same as cities), you can, of course, use the understanding:

citiesTruncated = {key.replace(" ", ""): value for key, value in cities.items()}

Not that in the second solution, even if you get a new one dict, the values ​​remain the same (not only equal) - this means that adding something to cities["Las Vegas"]will be added to citiesTruncated["LasVegas"], because they are the same.

0
source

Source: https://habr.com/ru/post/1622485/


All Articles