Python3遍历字典,找到特定的动态值

2024-04-26 14:35:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下内容:


wordPos = {}
words = [...] #Removed for simplicity

for i, word in enumerate(words):
     wordPos[i] = ({word[5]: word[4]})

最终变成:

>>> wordPos
{0: {1: 'Kontakt'},
 1: {2: 'email@domain.com'}, 
 2: {3: 'domain.com'}}

现在,我尝试在上面的字典中搜索,如果字符串/表达式存在,它应该返回值的“key”。你知道吗

例如:

string = "@domain.com"

if string in wordPos.values():
   print("The string: {}, exists in the dictionary. The key for this is: {}".format(string, key))

但是,我不知道如何在字典中搜索,并返回(值的)键。你知道吗

此外,我有点不确定是否需要使用RegEx来进行实际匹配?你知道吗

编辑

我可以看出,我需要更具体地考虑我要做什么。你知道吗

因此,基本上,我是逐字阅读整个文件,并将每个单词添加到字典中(以及特定单词的行号),从而得到以下结构:

lineNumber:word 

例如1:'Kontakt'

现在,我试图用这些信息来打开另一个文件并获取该文件的第一个字(在我的示例中,第一个字是@domain.com)。你知道吗

对于第一个单词,我想检查它是否存在于我的字典中(第一次出现)。如果有,我想返回行号。所以在我的例子中,对于单词@domain.com,应该返回的行号是2。你知道吗


Tags: 文件thekeyincomforstring字典
3条回答

一种可能性是使用python内置的sqlite3模块和FTS5全文索引:

import sqlite3

in_memory = sqlite3.connect(':memory:')
c = in_memory.cursor()
c.execute('CREATE VIRTUAL TABLE "ftsentry" USING FTS5 (line_no UNINDEXED, data, tokenize="unicode61 tokenchars \'.\'")')

c.execute("INSERT INTO ftsentry VALUES (?, ?)", (1, 'Kontakt'))
c.execute("INSERT INTO ftsentry VALUES (?, ?)", (2, 'email@domain.com'))
c.execute("INSERT INTO ftsentry VALUES (?, ?)", (3, 'domain.com'))
c.execute("INSERT INTO ftsentry VALUES (?, ?)", (4, 'domain@sample.com'))

l = [*c.execute('SELECT line_no, data FROM ftsentry WHERE data MATCH ? ORDER BY line_no ASC LIMIT 1', ('"@domain.com"', ))]
print(l)

l = [*c.execute('SELECT line_no, data FROM ftsentry WHERE data MATCH ?', ('"kontakt"', ))]
print(l)

印刷品:

[(2, 'email@domain.com')]
[(1, 'Kontakt')]

您可以创建如下函数。这将返回第一个匹配的行号。你知道吗

import re

input_dict = {
    0: {1: 'Kontakt'},
    1: {2: 'email@domain.com'},
    2: {3: 'domain.com'}
}

def search_word(regex):
    for k, v in input_dict.items():
        for _, v1 in v.items():
            if re.match(regex, v1):
                return k

print(search_word('domain.com')) # 2 (domain.com)
print(search_word('\w+@domain.com')) # 1 (email@domain.com)



输出:

2
1

如果确实要在字典中搜索动态值,则需要遍历这些项,检查这些值是否匹配,然后返回键。没办法用一种更像Python的方式。你知道吗

for key, value in wordPos.items():
    for inner_key, inner_value in value.items():
        if value == string:
            return key

如果已经有了一个单词数组,为什么不直接使用index方法呢?你知道吗

if string in words:
   print(f"The string: {string}, exists. The key for this is: {words.index(string)}")

如果字符串不存在,它将引发ValueError,因此可以通过以下方式避免if

try:
   print(f"The string: {string}, exists. The key for this is: {words.index(string)}")
except ValueError as e:
    pass

相关问题 更多 >