简体   繁体   English

将列表值与字典中的项目进行比较

[英]Comparing list values to items in a dictionary

Let's say I have a dictionary of all states abbreviations as a key, and the long names as the value: 假设我有一个所有状态缩写的字典作为键,而长名称作为值:

statesDict = {'AK': 'Alaska', 'AL': 'Alabama', 'AR': 'Arkansas',...}

I also have a list of pre-selected state abbreviations: 我还列出了预选的状态缩写:

statesAbbrv = ['AL', 'CA', 'CO', 'DE']

Based on the items in the cleanStates list, I want to chose only the values (the long names) for the state abbreviations keys in the stateNames dictionary and place them in a new list; 基于cleanStates列表中的项目,我想在stateNames字典中的状态缩写键选择值(长名称),并将其放置在一个新的列表; stateNames = [] So, the results of the comparison will look like this: stateNames = []因此,比较的结果将如下所示:

stateNames = ['Alabama', 'California', 'Colorado', 'Deleware']

I was thinking the following, but it's not working. 我在想以下内容,但没有用。 What am I doing wrong here? 我在这里做错了什么?

stateNames = []
for i in statesAbbrv:
    for k, v in statesDict:
        if stateDict[k] == stateAbbrv[i]:
            stateNames.append(stateDict(k))
print stateNames

Functionally 1 , you can use map 2 with dict.get : 从功能dict.get 1 ,可以将map 2dict.get

stateNames = list(map(statesDict.get, statesAbbrv))

If no match is found for an abbreviation, this will give None . 如果找不到匹配的缩写,则将给出None A stricter version which will yield KeyError : 一个更严格的版本将产生KeyError

stateNames = list(map(statesDict.__getitem__, statesAbbrv))

The latter is akin to the list comprehension, as [] is syntax to access __getitem__ : 后者类似于列表理解,因为[]是访问__getitem__语法:

stateNames = [statesDict[i] for i in statesAbbrv]

If you wish to supply a fallback if a key is not found, use a list comprehension with dict.get : 如果您希望在未找到密钥的情况下提供后备选项,请对dict.get使用列表dict.get

stateNames = [statesDict.get(i, 'Fallback State') for i in statesAbbrv]

1 Functional programming is a style of programming that treats computation as the evaluation of mathematical functions. 1函数式编程是一种将计算视为数学函数评估的编程风格。 See also Functional programming vs Object Oriented programming . 另请参见函数式编程与面向对象的编程

2 In Python 2.x, explicit list conversion is not necessary since map returns a list . 2在Python 2.x中,由于map返回list因此不需要显式list转换。 In Python 3, map returns an iterable, which will need to be exhausted via list . 在Python 3中, map返回一个可迭代的对象,需要通过list进行穷举。

This is a typical job for a list comprehension: 这是列表理解的典型工作:

stateNames = [statesDict.get(state, state) for state in statesAbbrv]
print(stateNames)
#['Alabama', 'CA', 'CO', 'DE']

Note that if a state abbreviation for some reason is not in the dictionary, it will be used as the state name itself. 请注意,如果由于某种原因而没有在字典中使用状态缩写,则它将用作状态名称本身。

stateNames = [stateDict[k] for k in statesAbbrv if k in stateDict]

使用list comprehensions

遍历列表statesAbbrv和查找值statesDict

statesNames = [statesDict[n] for n in statesAbbrv]
stateNames = []
for i statesAbbrv:
    for k, v in statesDict.iteritems():
        if stateDict[k] == stateAbbrv[i]:
            stateNames.append(stateDict(k))
print stateNames

You need to add iteritems() to make the dictionary iterable on python 2.7. 您需要添加iteritems()才能使字典在python 2.7上可迭代。

Serious typo errors in your question. 您的问题中存在严重的拼写错误。 Well, here is the answer (Just after removing errors in your own code): 好的,这就是答案(只是在消除了您自己的代码中的错误之后):

statesDict = {'AK': 'Alaska', 'AL': 'Alabama', 'AR': 'Arkansas'}
statesAbbrv = ['AL', 'AK']

stateNames = []
for i in statesAbbrv:
    for k in statesDict.keys():
        if k == i:
            stateNames.append(statesDict[k])
print (stateNames)
stateNames = [statesDict.get(i) for i in statesAbbrv]

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

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