从具有相似键值的字典列表中提取信息

2024-04-26 06:54:51 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法从词典列表中提取特定信息? 例如,我希望获取StartInterface,因为StartNode是router3,EndNode是router4

abc = 
 [{'StartNode': 'router1',
  'EndNode': 'router2',
  'StartInterface': 'Po1',
  'EndInterface': 'Po1'},
 {'StartNode': 'router3',
  'EndNode': 'router4',
  'StartInterface': 'Po8',
  'EndInterface': 'Po8'}]

Tags: 信息列表词典abc办法router1po1startnode
3条回答

要做您想做的事情,需要遍历字典列表以找到一个匹配的字典(如果有的话)

以下是一种暴力(通过线性搜索)方式:

abc = [{'StartNode': 'router1',
       'EndNode': 'router2',
       'StartInterface': 'Po1',
       'EndInterface': 'Po1'},
      {'StartNode': 'router3',
       'EndNode': 'router4',
       'StartInterface': 'Po8',
       'EndInterface': 'Po8'}]

def get_startinterface(objects, startnode, endnode):
    """ Return StartInterface of object with given StartNode and EndNode.
    """
    for obj in objects:
        if obj['StartNode'] == startnode and obj['EndNode'] == endnode:
            return obj['StartInterface']
    else:
        return None  # Not found.

print(get_startinterface(abc, 'router3', 'router4'))  # -> Po8

如果有大量词典和/或这项工作将非常频繁地进行,那么构建查找表并使用它的开销将是值得的,因为它消除了每次进行相对缓慢的线性搜索的需要:

# Get better search performance by building and using a lookup table.

def get_startinterface(table, startnode, endnode):
    """ Return StartInterface of object with given StartNode and EndNode.
    """
    match = table.get((startnode, endnode), {'StartInterface': None})
    return match['StartInterface']

lookup_table = {(obj['StartNode'], obj['EndNode']): obj for obj in abc}

print(get_startinterface(lookup_table, 'router3', 'router4'))  # -> Po8

您可以这样尝试:

abc = [
        {
            'StartNode': 'router1',
            'EndNode': 'router2',
            'StartInterface': 'Po1',
            'EndInterface': 'Po1'
        },
        {
            'StartNode': 'router3',
            'EndNode': 'router4',
            'StartInterface': 'Po8',
            'EndInterface': 'Po8'
        }
    ]

for item in abc:
    print('{} for {}: startnode: {}, endnode: {}'.format(
        item['StartInterface'],
        item['StartNode'],
        item['StartInterface'],
        item['EndInterface']
    ))

输出:

Po1 for router1: startnode: Po1, endnode: Po1
Po8 for router3: startnode: Po8, endnode: Po

8个

您可以与列表中的所有项目交互,并按您的意愿打印格式。有关详细信息,请参阅格式文档 本文可能有用: https://www.learnpython.org/en/String_Formatting

它是一个对象列表,所以要获得所需的内容,可以转到列表中对象的索引,然后使用键,可以获得它的值

abc[1]["StartNode"] #router3
abc[1]["EndNode"] #router4

给你的建议是,每当你在这里发布问题时,一定要分享你尝试过的最低限度的实现。看看“如何提问”部分。谢谢

相关问题 更多 >