Python-当“值”为列表时检查字符串是否在字典值中

时间:2018-07-20 16:04:12

标签: python-3.x list dictionary

我正在尝试解决以下问题:我在圣经中创建了一系列书籍。我还创建了一个词典,其中包含一个键和一个值,该值是对所创建列表的引用。

我想看看字典中是否存在字符串值,如果存在,则返回该值的键。

这是我的代码:

# Dict List for bible
BIBLE_BOOKS_LIST_DICT = [
("Genesis"), ("Exodus"), ("Leviticus"),
("Numbers"), ("Deuteronomy"), ("Joshua"),
("Judges"), ("1 Samuel"), ("2 Samuel"),
("1 Kings"), ("2 Kings"), ("1 Chronicles"),
("2 Chronicles"), ("Ezra"), ("Nehemiah"),
("Esther"), ("Job"), ("Psalms"), ("Proverbs"),
("Ecclesiastes"), ("Song of Solomon"),
("Isaiah"), ("Jeremiah"), ("Lamentations"),
("Ezekiel"), ("Daniel"), ("Hosea"), ("Joel"),
("Amos"), ("Obadiah"), ("Jonah"), ("Micah"),
("Nahum"), ("Habakkuk"), ("Zephaniah"),
("Haggai"), ("Zechariah"), ("Malachi"),
("Matthew"), ("Mark"), ("Luke"), ("John"),
("Acts"), ("Romans"), ("1 Corinthians"),
("2 Corinthians"), ("Galatians"), ("Ephesians"),
("Philippians"), ("Colossians"), ("1 Thessalonians"),
("2 Thessalonians"), ("1 Timothy"), ("2 Timothy"),
("Titus"), ("Philemon"), ("Hebrews"), ("James"),
("1 Peter"), ("2 Peter"), ("1 John"), ("2 John"),
("3 John"), ("Jude"), ("Revelation")
]

# Dict for bible categories
BIBLE_BOOKS_DICT = {
'The Law':BIBLE_BOOKS_LIST_DICT[:5],
'OT History':BIBLE_BOOKS_LIST_DICT[5:16],
'Poetry':BIBLE_BOOKS_LIST_DICT[16:21],
'Major Prophets':BIBLE_BOOKS_LIST_DICT[21:26],
'Minor Prophets':BIBLE_BOOKS_LIST_DICT[26:38],
'Gospels':BIBLE_BOOKS_LIST_DICT[38:42],
'NT History':BIBLE_BOOKS_LIST_DICT[42:43],
'Pauline Epistles':BIBLE_BOOKS_LIST_DICT[43:52],
'Pastoral Letters':BIBLE_BOOKS_LIST_DICT[52:55],
'General Epistles':BIBLE_BOOKS_LIST_DICT[55:64],
'Prophecy':BIBLE_BOOKS_LIST_DICT[64:65]
}

我已经为此工作了几个小时,但没有找到任何解决方案! 我的逻辑是

if "Matthew" in BIBLE_BOOKS_DICT.values():
    print *the key related to that value*

谢谢!

3 个答案:

答案 0 :(得分:1)

如果您希望能够按书查找并返回类别,则需要将书作为键存储在字典中:

BIBLE_BOOKS_DICT = {
"Matthew": 'Gosphels'
"Revelation": 'Prophecy'

# etc...

"1 John": 'Gosphels'

字典能够在非常快的运行时间(例如常量)中查找给定键的值。但是要查找给定值的键,从本质上讲,您必须遍历所有值,然后将找到的值反向映射到其键。使用上述字典,您的查找逻辑将是:

# Look up the key, and assign its value to a variable
result = BIBLE_BOOKS_DICT.get("Matthew")

# Searched keys that don't exist in the dictionary will return None.
if result is not None:
    print result

让我知道这是否没有任何意义,我很乐意进一步阐述!

答案 1 :(得分:0)

如何使用dict.items()方法:

for key, value in BIBLE_BOOKS_DICT.items():
    if "Matthew" in value:
        print(key)

答案 2 :(得分:0)

有人更快。

input = 'Matthew'
for k, v in BIBLE_BOOKS_DICT.items():
    if input in v:
        print(k)

但是我有一个功能。

def get_cat(book):
    for k, v in BIBLE_BOOKS_DICT.items():
        if input in v:
            return k

print(get_cat('Matthew'))

输出

Gospels
Gospels