【问题标题】:Python dictionary convert to lowercase?Python字典转换为小写?
【发布时间】:2012-10-17 15:04:00
【问题描述】:

我有这个需要转换为小写的 Python 字典。字典包含需要与不区分大小写的输入对应的数据,例如所以它适用于 resp = 'GBR' 或 'gbr'。希望我在这里有意义。任何帮助将不胜感激!

resp = raw_input('Which country is ' + record['name'] + ' in? ')
        print " "
        valid = {'GBR': ['GBR',
                        'United Kingdom',
                        'UK',
                        'Great Britain and Northern Island',
                        'GB'
                        ],
                'IRL': ['IRL',
                        'Eire',
                        'Republic of Ireland'
                        ]
            }
        if resp in valid[record['sov']]:
            answ = 'Yes, ' + record['name'] + ' is in the ' + resp

【问题讨论】:

  • 但是我如何让它适用于其他输入,例如英国、爱尔兰、爱尔兰等?谢谢
  • record的值是多少?

标签: python dictionary uppercase lowercase


【解决方案1】:

如果它需要对应不区分大小写的输入,我建议您在比较输入和字典值时简单地添加一个.lower() 调用,而不是为此创建/转换第二个字典。

但是,鉴于您的字典已经是大写的,我会使用 .upper() 将您的输入转换为大写以匹配您的字典,而不是反其道而行之

【讨论】:

  • 它似乎不起作用:resp = raw_input('Which country is ' + record['name'] + ' in?').lower()
  • .lower() 将字符串转换为小写。所以你会用它作为resp = raw_input('Which country is ' + record['name'].lower() + ' in? ')
  • 但是,鉴于您的字典已经是大写的,我会使用 .upper() 将您的输入转换为大写以匹配您的字典,而不是反其道而行之
  • 很高兴听到!如果您觉得有帮助,请考虑接受答案 =)
【解决方案2】:

基本上将响应的小写版本与正确答案的小写版本进行比较。

但是从您的问题中,有几件事并不完全清楚:

您在records 中究竟存储了什么? 在确认“是的,...在...中”时应该使用哪个国家/地区名称? 您希望将用户响应与有效同义词列表进行匹配,对吗?

如果我要写一个城市流行问答游戏,我可能会这样做:

import random

cities = {'Dublin': 'IRL',
          'London': 'GBR',
          }

country_synonyms = {'GBR': ['United Kingdom',
                            'GBR',
                            'UK',
                            'Great Britain and Northern Island',
                            'GB',
                            ],
                    'IRL': ['Republic of Ireland',
                            'IRL',
                            'Eire',
                            ]
                    }

# Pick a random city from our dicts' keys
challenge = random.choice(cities.keys())

# Country code of the correct response, e.g. 'GBR'
correct_cc = cities[challenge]

# Assume the canonical name for a country is first in the list of synonyms
correct_name = country_synonyms[correct_cc][0]

response = raw_input('Which country is %s in? ' % challenge)

# Clean any whitespace
response = response.strip()

lowercase_synonyms = [s.lower() for s in country_synonyms[correct_cc]]

if response.lower() in lowercase_synonyms:
    answer = "Yes, %s is in the %s." % (challenge, correct_name)
else:
    answer = "Sorry, that's wrong. %s is in the %s." % (challenge, correct_name)

print answer

这一行

lowercase_synonyms = [s.lower() for s in country_synonyms[correct_cc]]

使用列表推导将列表country_synonyms[correct_cc] 中的每个字符串转换为小写。另一种选择是使用map:

import string
# ...
lowercase_synonyms = map(string.lower, country_synonyms[correct_cc])

这会将函数string.lower 映射到列表country_synonyms[correct_cc] 中的每个项目。

【讨论】:

    【解决方案3】:

    其他答案显示了一种正确的方法,但是如果您想将 dict 转换为小写,这是最简单但不是最有效的方法:

    >>> import ast
    >>> d
    {'GBR': ['GBR', 'United Kingdom', 'UK', 'Great Britain and Northern Island', 'GB'], 'IRL': ['IRL', 'Eire', 'Republic of Ireland']}
    >>> ast.literal_eval(str(d).lower())
    {'gbr': ['gbr', 'united kingdom', 'uk', 'great britain and northern island', 'gb'], 'irl': ['irl', 'eire', 'republic of ireland']}
    

    编辑:eval 中的全局参数。

    编辑 2:使用安全的“literal_eval”:

    这可用于安全地评估来自不受信任来源的包含 Python 表达式的字符串,而无需自己解析值。

    【讨论】:

    • 你应该使用eval来做这样的事情!如果d 可以包含不受信任的用户输入,那么您只是在代码中添加了一个安全漏洞。
    • 现在用literal_eval怎么样?
    • 现在您导入ast 模块只是为了将字典转换为小写?对不起,但仍然感觉像用大锤敲碎坚果。但是 +0 因为它是安全的,当然是正确的。
    • 最后一个问题,如果我使用 eval(..., {}) 来限制访问怎么办?
    • 我个人可能会使用map(string.lower, lst)。只使用内置函数,简洁明了。不像你的那样处理字典键(国家代码)。
    猜你喜欢
    • 2018-10-04
    • 2013-02-19
    • 2016-10-16
    • 1970-01-01
    • 1970-01-01
    • 2015-08-24
    • 2017-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多