簡體   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