M.salameh
M.salameh

Reputation: 109

Get the key that has specific attribute of its value

I have dictionary with list of objects as values.

class Device_Terminals():
    """Class for define object for each device"""
    def __init__(self, device_name, source, drain):
        self.device_name = device_name
        self.source = source
        self.drain = drain

device = Device_Terminals(line[0], line[1], line[3])
if line[2] not in devices_dict:
        devices_dict[line[2]] = []
devices_dict[line[2]].append(device)

I want to return the key whose one of its objects has specific name, the dictionary looks like this

{A1:[ MNA1 X_N1 VSS, MPA1_1 X X_P1_1, MPA1_2 X X_P1_2, MPA1_3 X X_P1_3, MPA1_4 X X_P1_4, MPA1_5 X X_P1_5, MPA1_6 X X_P1_6, MPA1_7 X X_P1_7], 'A3': [MNA3 X_N1 VSS, MPA3_1 X_P2_1 VDD, MPA3_2 X_P2_2 VDD, MPA3_3 X_P2_3 VDD, MPA3_4 X_P2_4 VDD, MPA3_5 X_P2_5 VDD]}

each element of the lists is an object. how can I return the key whose value of the

 device_name == MPA3_3: 
   return key

Upvotes: 0

Views: 779

Answers (2)

dalonlobo
dalonlobo

Reputation: 503

You can create defaultdict from collections instead of checking if the key exists and then appending to it.

from collections import defaultdict
devices_dict = defaultdict(list)

To add to this dict:

device = Device_Terminals(line[0], line[1], line[3])
devices_dict[line[2]].append(device)

To search its values, you put a simple loop over the dictionary:

# your search term
search_val = 'device_name'
for key, devices in devices_dict.items():
    for device in devices:
        if search_val == device.device_name:
            print(key)

Upvotes: 1

boonwj
boonwj

Reputation: 356

If you are trying to do dict lookup using its values. Try look at the solution of this previously answered question.

Get key by value in dictionary

Upvotes: 0

Related Questions