0

How can I get all keys which contain the specific value in dictionary?

For Example:- This is dictionary which holds simple data.

{'h':['123,'4'], 'm':['456':'4'], 'a':['123,'4']}

If I enter a value of 4, prints all the keys which containing the number. This is the output.

{'h', 'm', 'a'}
Adil B
  • 14,635
  • 11
  • 60
  • 78
Hassan Salah
  • 157
  • 2
  • 7

2 Answers2

4

Since your result is a set, I would use a set constructor.

Since the value of your set depends on an iteration of your input data, I would pass a generator expression to the set constructor.

search_term = '4'
data = {'h':['123','4'], 'm':['456','4'], 'a':['123','4']}
result = set(k for k,v in data.items() if search_term in v)
assert result == {'h', 'm', 'a'}
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • Since the elements of the set are keys from the dictionary, wouldn't a list be sufficient (since we know the elements are unique)? – pault Dec 14 '17 at 17:33
  • 1
    I would think so, yes. But the OP's question clearly displays a set as the result. – Robᵩ Dec 14 '17 at 17:33
  • @pault why would you prefer a list of unique elements over a set? – Tadhg McDonald-Jensen Dec 14 '17 at 19:38
  • @TadhgMcDonald-Jensen just asking. I initially thought there might have been some extra overhead for a set vs. a list, but that doesn't seem to be the case. – pault Dec 14 '17 at 19:45
1

What about without loop ?

Everyone is going to give you loop soution , let's try something different :

data is:

your_data = {'h':['123','4'], 'm':['456','4'], 'a':['123','4']}

One line without loop:

print(set(filter(lambda y:y,map(lambda x:x if '4' in your_data.get(x) else None,your_data))))

output:

{'a', 'm', 'h'}

Best way is use a function :

def search_values(x,dict_data):
    final_list=[]
    for key,value in dict_data.items():
        if x in value:
            final_list.append(key)

    return set(final_list)

print(search_values('4',your_data))

output:

{'a', 'm', 'h'}
Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88