简体   繁体   English

Python:编辑字典键 - 使用剥离方法

[英]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 ' .您可以看到的键有一个字符串,其中包含开头和结尾的空格: ' 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() ?也许使用replace(" ", "")方法或strip()

When trying the strip method I get the error:尝试 strip 方法时出现错误:

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:使用dict理解:

  • Incidentally, don't use python data types as the name of your variables (eg Dict )顺便说一句,不要使用 python 数据类型作为变量的名称(例如Dict
  • Dict Comprehension听写理解
  • When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the .items() method.遍历字典时,可以使用.items()方法同时检索key和对应的value
  • .strip only on the key .strip只在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.您不能直接编辑键,因为字典是 hash 表。 Changing the key changes its hash, so you have two conceptual options.更改密钥会更改其 hash,因此您有两个概念选项。

The first is to replace the entire dictionary, which is more pythonic in my opinion:首先是替换整个字典,在我看来这更pythonic:

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.第二种选择是保留相同的字典 object,但将映射一一替换。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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