繁体   English   中英

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

[英]Python - Check if String is in Dictionary Value when Value is a list

我正在尝试解决以下问题:我创建了一个圣经书籍清单。 我还创建了一个字典,它有一个键和一个值,它是对创建的列表的引用。

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

这是我的代码:

# 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*

谢谢!

怎么样,使用dict.items()方法:

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

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

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

如果其中任何一个没有意义,请告诉我,我很乐意进一步详细说明!

有人更快。

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 book in v:
            return k

print(get_cat('Matthew'))

输出

Gospels
Gospels

暂无
暂无

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

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