简体   繁体   中英

Python: Editing Dictionary Keys - Using Strip Method

I have a dictionary as seen below:

Dict = {' Chicago ': 4, ' Washington ': 9, ' LA ': 26, ' Boston ': 12, ' Seattle ': 2}

I want to edit the key of each entry, but not the values. The keys you can see have a string which includes whitespace at the start and end: ' Chicago ', ' Washington ', ' LA ' .

I want to group through and strip the white space from the keys. Leaving me with the following dictionary.

Dict = {'Chicago': 4, 'Washington': 9, 'LA': 26, 'Boston': 12, 'Seattle': 2}

How would I do this? Maybe using the replace(" ", "") method or the strip() ?

When trying the strip method I get the error:

AttributeError: 'int' object has no attribute 'strip'

Your error suggests you tried converting the values instead of the keys, but anyway, this should work:

new_dict = {key.strip(): value for key, value in old_dict.items()}

Use a dict comprehension:

  • Incidentally, don't use python data types as the name of your variables (eg Dict )
  • Dict Comprehension
  • When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the .items() method.
  • .strip only on the key
data = {' Chicago ': 4, ' Washington ': 9, ' LA ': 26, ' Boston ': 12, ' Seattle ': 2}

data = {k.strip(): v for (k, v) in data.items()}

>>> {'Chicago': 4, 'Washington': 9, 'LA': 26, 'Boston': 12, 'Seattle': 2}

The easiest way to do this is:

Dict2 = {}
for key in Dict:
   Dict2[key.strip()] = Dict[key]
Dict = Dict2

Or you can use comprehension to ease it:

Dict = {key.strip():value for (key,value) in Dict}

I think the easiest way to do it is by looping the keys, as follows. I've commented to the code along the way.

#Your dictionary
dict = {' Chicago ': 4, ' Washington ': 9, ' LA ': 26, ' Boston ': 12, ' Seattle ': 2}

#Puts all keys of the dictionary into a list
keys = list(dict)

#iterates over dictionary keys
for key in keys:

    #for every key, we make a new dictionary item with the 'stripped' key and remove the old one
    dict[key.strip()] = dict[key]
    del dict[key]

print(dict)

This gives us the same dictionary and same values, but with the leading/trailing whitespaces removed from the keys:

{'Chicago': 4, 'Washington': 9, 'LA': 26, 'Boston': 12, 'Seattle': 2}

You can't edit the keys directly since dictionaries are hash tables. Changing the key changes its hash, so you have two conceptual options.

The first is to replace the entire dictionary, which is more pythonic in my opinion:

dct = {k.strip(): v for k, v in dct.items()}

Or alternatively:

dct = {k.strip(): dct[k] for k in dct}

The second option is to keep the same dictionary object, but replace the mappings one by one. This is complicated by the fact that you shouldn't modify the keys, especially with deletion, while you iterate over the dictionary. You have to make a separate copy of the original keys first and work with that:

for k in list(dct):
    v = dct.pop(k)
    dct[k.strip()] = v

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM