如何比较一个python字典键和另一个字典键的一部分?类似于.contains()函数 [英] How to compare a python dictionary key with a part of another dictionary's key? something like a .contains() function

查看:217
本文介绍了如何比较一个python字典键和另一个字典键的一部分?类似于.contains()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的大部分小型项目都使用字典可以正常工作,因此现在更改它基本上意味着从头开始.

Most of my small-scale project worked fine using dictionaries, so changing it now would basically mean starting over.

假设我有两个不同的字典(dict1和dict2).

Let's say I have two different dictionaries(dict1 and dict2).

一个人:

{'the dog': 3, 'dog jumped': 4, 'jumped up': 1, 'up onto': 8, 'onto me': 13}

第二个是:

{'up': 12, 'dog': 22, 'jumped': 33}

我想找到第一本字典中第一个单词与第二个字典中的单词相等的地方.这两个字典的长度不同,如示例中所示.然后,在找到它们之后,将它们的值相除.

I want to find wherever the first word of the first dictionary is equal to the word of the second one. These 2 dictionaries don't have the same length, like in the example. Then after I find them, divide their values.

所以我想做的是,使用一些Java语言:

So what I want to do, sort of using a bit of Java is:

for(int i = 0;i<dict1.length(),i++){
    for(int j = 0;j<dict2.length(),j++){
        if(dict1[i].contains(dict2[j]+" ") // not sure if this works, but this
                                           // would theoretically remove the 
                                           // possibility of the word being the 
                                           // second part of the 2 word element
            dict1[i] / dict2[j]

到目前为止,我一直在尝试制作4个不同的列表. dict1键的列表,dict1值的列表和dict2的列表.然后我意识到我什至不知道如何检查dict2是否具有与dict1类似的元素.

What I've tried so far is trying to make 4 different lists. A list for dict1 keys, a list for dict1 values and the same for dict2. Then I've realized I don't even know how to check if dict2 has any similar elements to dict1.

我试图在字典中增加一个额外的值(一种索引),所以它会使我进入某个位置,但是事实证明,dict2.keys()也不是可迭代的.反过来让我相信使用4个不同的列表并尝试以某种方式对其进行比较是非常错误的.

I've tried making an extra value in the dictionary (a sort of index), so it would kind of get me somewhere, but as it turns out dict2.keys() isn't iterable either. Which would in turn have me believe using 4 different lists and trying to compare it somehow using that is very wrong.

推荐答案

字典根本没有任何设施可以处理部分键.键是不透明的对象.他们在那里或不在那里.

Dictionaries don't have any facilities at all to handle parts of keys. Keys are opaque objects. They are either there or not there.

是的,您将遍历第一个词典中的所有键,提取第一个单词,然后测试另一个词典是否将第一个单词作为键:

So yes, you would loop over all the keys in the first dictionary, extract the first word, and then test if the other dictionary has that first word as a key:

for key, dict1_value in dict1.items():
    first_word = key.split()[0]  # split on whitespace, take the first result
    if first_word in dict2:
        dict2_value = dict2[first_word]
        print(dict1_value / dict2_value)

因此,这将占用dict1中的每个键,分割出第一个单词,并测试该单词是否是dict2中的键.如果是,则获取值并打印结果.

So this takes every key in dict1, splits off the first word, and tests if that word is a key in dict2. If it is, get the values and print the result.

如果您需要更频繁地测试那些第一个单词,则可以通过首先构建另一种结构来创建一个从第一个单词到整个键的索引的方法来使其效率更高.只需将第一个词典的每个键的第一个单词存储在新词典中:

If you need to test those first words more often, you could make this a bit more efficient by first building another structure to to create an index from first words to whole keys. Simply store the first words every key of the first dictionary, in a new dictionary:

first_to_keys = {}
for key in dict1:
    first_word = key.split()[0]
    # add key to a set for first_word (and create the set if there is none yet)
    first_to_keys.setdefault(first_word, set()).add(key)

现在first_to_key是第一个单词的字典,指向各组键(因此,如果同一第一个单词出现不止一次,则您将得到 all 个完整键,而不仅仅是其中一个) .一次建立该索引(每次在dict1中添加或删除键时都要更新值,因此请随时进行更新).

Now first_to_key is a dictionary of first words, pointing to sets of keys (so if the same first word appears more than once, you get all full keys, not just one of them). Build this index once (and update the values each time you add or remove keys from dict1, so keep it up to date as you go).

现在您可以将该映射与其他词典进行比较:

Now you can compare that mapping to the other dictionary:

for matching in first_to_key.keys() & dict2.keys():
    dict2_value = dict2[matching]
    for dict1_key in first_to_key[matching]:
        dict1_value = dict1[dict1_key]
        print(dict1_value / dict2_value)

这使用两个字典中的键作为 sets dict.keys()对象是词典视图,使您可以应用设置操作. &为您提供两个字典键集的 intersection ,因此,这两个字典键集中都存在所有键.

This uses the keys from two dictionaries as sets; the dict.keys() object is a dictionary view that lets you apply set operations. & gives you the intersection of the two dictionary key sets, so all keys that are present in both.

仅在需要更频繁地使用第一个单词时,才需要使用第二个选项.它为您提供了另一个方向的快速路径,因此您可以遍历dict2,然后再次快速回到第一个词典.

You only need to use this second option if you need to get at those first words more often. It gives you a quick path in the other direction, so you could loop over dict2, and quickly go back to the first dictionary again.

这篇关于如何比较一个python字典键和另一个字典键的一部分?类似于.contains()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆