Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Some help with Dictionaries
#1
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
Reply
#2
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']
Oshadha likes this post
Reply
#3
(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?
Reply
#4
(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.
Oshadha likes this post
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020