python - 列表项与字典比较的单行解决方案

标签 python list dictionary

region_dict = {'france':'West', 'germany':'Central', 'italy':'South', 'poland':'East', 'norway':'North'}

mylist = ['FRANCE','gERMANY', 'iTaLy', 'poland', 'Norway']

for item in mylist:
    if item.lower() in region_dict:
         region = region_dict[item.lower()]
         print(region)

我正在尝试将列表值与字典键进行比较并获取字典值。这可行,但是有没有办法在一行中完成它?在我看来,除了看起来更好之外没有其他真正的原因。

我尝试过这样做:

region = item for item in mylist if item.lower() in region_dict

但这没有用。

最佳答案

region = [region_dict.get(item.lower()) for item in mylist if item.lower() in region_dict.keys()]

关于python - 列表项与字典比较的单行解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60416393/

相关文章:

python - 如何解耦 Django 和 Celery?

list - 如何在 pyspark 的列表中找到最频繁出现的元素?

c++ - STL list::splice - 迭代器有效性

Python - 如何将列表转换为日志(列表)

javascript - 谷歌地图折线 : Mark the two Polyline coordinates that contain the clicked LatLng

python - 列表操作(可变或不可变)?

python - 如何在 wxPython 中制作一个简单的文件浏览器?

python - 替换格式为 csv 行的字符串中的项目

html - CSS Sprite 和图像映射

c++ - std::map 的 const_cast 问题