python - 将字典中列表的值转换为大写/小写

标签 python python-2.7

我有一个 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/

相关文章:

通过 IDLE 运行的 Python 脚本没有输出

python - 如何使用列的格式字符串显示 float 的pandas DataFrame?

python - 是否有在 cygwin 上安装 Kivy 的说明?

python-2.7 - Python 2.7 pip install lxml UnicodeDecodeError

python logging.config 不可用?

python - 将python编解码器转换为文本

python - 如何通过 yfinance 下载数据修复此错误

python - 需要快速更新 Django 模型与其他两个模型之间的差异

python - 随机使用比较运算符?

python - 使用 Ansible Python API,我如何才能访问我的代码中的任务级输出?