Python Forum
Some help with Dictionaries - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Some help with Dictionaries (/thread-32068.html)



Some help with Dictionaries - Oshadha - Jan-19-2021

Script,
a_dic = {
    "a" :   [":D", ":)"],
    "b" :   ["lol", "XD"],
    "c" :   ["lol", ">:"],
    "d" :   [":)", "XD"]
}
How do I search for values and print out their key?

In a_dict i want to search ":)" and print its keys.

For example :
Search_item = ":)"
Output:
d a



RE: Some help with Dictionaries - bowlofred - Jan-19-2021

The dictionary itself doesn't have any features that allow you to search a key based on a value. All you can do is loop over every key/value and keep track of keys where the value meets your criteria. As the dictionary grows large, this operation will become more expensive.



a_dic = {
    "a" :   [":D", ":)"],
    "b" :   ["lol", "XD"],
    "c" :   ["lol", ">:"],
    "d" :   [":)", "XD"]
}

search_item = ":)"

match_keys = [k for k,v in a_dic.items() if search_item in v]
print(match_keys)
Output:
['a', 'd']



RE: Some help with Dictionaries - Oshadha - Jan-19-2021

(Jan-19-2021, 06:46 AM)bowlofred Wrote: The dictionary itself doesn't have any features that allow you to search a key based on a value. All you can do is loop over every key/value and keep track of keys where the value meets your criteria. As the dictionary grows large, this operation will become more expensive.



a_dic = {
    "a" :   [":D", ":)"],
    "b" :   ["lol", "XD"],
    "c" :   ["lol", ">:"],
    "d" :   [":)", "XD"]
}

search_item = ":)"

match_keys = [k for k,v in a_dic.items() if search_item in v]
print(match_keys)
Output:
['a', 'd']

When you mean expensive, you mean from time & resources right?


RE: Some help with Dictionaries - DeaD_EyE - Jan-19-2021

(Jan-19-2021, 06:57 AM)Oshadha Wrote: When you mean expensive, you mean from time & resources right?

A dict consumes more memory as a tuple or list.
Creating a dict is slow. To find a key in a dict is very fast independent of the dict size.

You've to think about this problem, if the size is big enough, but not for 4 elements.

This overhead is important if you work later with data where you have data shaped like 1.000.000 x 10.