获取具有其值的特定属性的键
Get the key that has specific attribute of its value
我有一个以对象列表作为值的字典。
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)
我想要 return 其对象之一具有特定名称的键,字典如下所示
{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]}
列表中的每个元素都是一个对象。
我如何 return 其值为
的键
device_name == MPA3_3:
return key
如果您尝试使用其值进行字典查找。尝试查看这个先前回答的问题的解决方案。
Get key by value in dictionary
您可以从 collections
创建 defaultdict
而不是检查密钥是否存在然后附加到它。
from collections import defaultdict
devices_dict = defaultdict(list)
要添加到这个字典:
device = Device_Terminals(line[0], line[1], line[3])
devices_dict[line[2]].append(device)
要搜索其值,您可以在字典上放置一个简单的循环:
# 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)
我有一个以对象列表作为值的字典。
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)
我想要 return 其对象之一具有特定名称的键,字典如下所示
{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]}
列表中的每个元素都是一个对象。 我如何 return 其值为
的键 device_name == MPA3_3:
return key
如果您尝试使用其值进行字典查找。尝试查看这个先前回答的问题的解决方案。
Get key by value in dictionary
您可以从 collections
创建 defaultdict
而不是检查密钥是否存在然后附加到它。
from collections import defaultdict
devices_dict = defaultdict(list)
要添加到这个字典:
device = Device_Terminals(line[0], line[1], line[3])
devices_dict[line[2]].append(device)
要搜索其值,您可以在字典上放置一个简单的循环:
# 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)