我有一个 python
字典,如下所示
my_dict = {u'customer': [u'GS808E', u'GS810EMX'], u'tablets': [u'Apple IPAD PRO', u'Apple IPAD MINI', u'IPAD'], u'gaming_consoles': [u'SONY PLAYSTATION 4', u'XBOX ONE S', u'PLAYSTATION'], u'range_of_days': 14 }
我想将此字典
中的所有值
转换为小写
或大写
我已经做了如下。
new_dict = {k:[i.lower() for i in v] for k,v in my_dict.items()}
我在 Python 2.7
中收到以下错误
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <dictcomp>
TypeError: 'int' object is not iterable
最佳答案
@User9367133,不要使用字典理解。它不会更新 my_dict
,而是会获取 my_dict
的元素并创建新字典。
一旦您选择了字典中任何键所指向的任何值,请检查它是否是一个列表。如果是列表,则将字符串列表转换为小写。
如果您想最初更新 my_dict
的内容,请按此操作。
Try it online at http://rextester.com/KMSLJ9545.
my_dict = {u'customer': [u'GS808E', u'GS810EMX'], u'tablets': [u'Apple IPAD PRO', u'Apple IPAD MINI', u'IPAD'], u'gaming_consoles': [u'SONY PLAYSTATION 4', u'XBOX ONE S', u'PLAYSTATION'], u'range_of_days': 14 };
for key in my_dict:
if type(my_dict[key]) == type([]):
for index, item in enumerate(my_dict[key]):
my_dict[key][index] = item.lower();
print my_dict
» 输出
{'gaming_consoles': ['sony playstation 4', 'xbox one s', 'playstation'], 'range_of_days': 14, 'tablets': ['apple ipad pro', 'apple ipad mini', 'ipad'], 'customer': ['gs808e', 'gs810emx']}
如果您仍然喜欢使用字典理解来创建与上面相同的新字典,那么您可以尝试下面的代码(但这不是您想要的)。
Try it online at http://rextester.com/CEZ39339.
my_dict = {u'customer': [u'GS808E', u'GS810EMX'], u'tablets': [u'Apple IPAD PRO', u'Apple IPAD MINI', u'IPAD'], u'gaming_consoles': [u'SONY PLAYSTATION 4', u'XBOX ONE S', u'PLAYSTATION'], u'range_of_days': 14 };
my_dict = { key: ([item.lower() for item in my_dict[key]] if type(my_dict[key]) == type([]) else my_dict[key]) for key in my_dict}
print my_dict
» 输出
{u'customer': [u'gs808e', u'gs810emx'], u'tablets': [u'apple ipad pro', u'apple ipad mini', u'ipad'], u'gaming_consoles': [u'sony playstation 4', u'xbox one s', u'playstation'], u'range_of_days': 14}
关于python - 将字典中列表的值转换为大写/小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50808495/