开发者

Python3 obtain keys from values?

It seems like this is a common problem, but I can't seem to find a solution.

I have a Python3 script containing two dictionaries sqldict and hitsdict. This code outputs dictionary values, if sqldict[value][0] == hitsdict[thing][1].

for value in sqldict:
        for thing in hitsdict:
            if sqldi开发者_运维问答ct[value][0] == hitsdict[thing][1]:
                print(hitsdict[thing][1],sqldict[value][5])

I would also like to get the keys that are associated with the values that match the sqldict[value][0] == hitsdict[thing][1] comparison, but I can't seem to figure out how to get the associated keys? I was trying to do something like this:

for key, value in sqldict.items():
        for thing in hitsdict:
            if sqldict[value][0] == hitsdict[thing][1]:
                            print(key,hitsdict[thing][1],sqldict[value][5])

Can anyone explain what my problem is and how I can get the keys from values that pass my, if sqldict[value][0] == hitsdict[thing][1] comparison? Thank you!

EDIT: One idea I had is to add the key as an addition value. Is there another more pythonic way?


You are finding values by looping through the items in the dictionary. That's the wrong way. The whole purpose of the dictionary is to use the keys to look things up.

In short, your datastructure is completely messed up. Since we don't know how it looks, we can't tell you how it should look, but on the other hand, you have the word "sql" in one of the values.

May I suggest you use SQL queries to do whatever you do instead?


A dictionary lookup is "by key" not "by value."

>>> d = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
>>> for key in d:
...     print key
... 
key3
key2
key1

I'm sorry, but I can't think of any other answer but "You are doin it rong!"


You can use what I shall call "inverse dicts". My idea is, you create two dictionaries:

dict1 = {key1: value1, key2: value2, ...}
dict1_inv = {value1: key1, value2: key2, ...}

Now you can quickly get value associated with each key and the inverse: key associated with each value.

I don't know if this is "Pythonic", but from what I understand, should address your problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜