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

时间:2019-03-15 16:28:45

标签: python python-3.x

是否可以从字典列表中提取特定信息? 例如,我希望获取StartInterface,因为StartNode是router3,EndNode是router4

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

3 个答案:

答案 0 :(得分:1)

它是对象的列表,因此,要获取所需的内容,可以转到列表中对象的索引,并使用键获取其值。

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

为您提供的建议是,每当您在此处发布问题时,都应分享您尝试过的最低实现。看一下“如何提问”部分。谢谢

答案 1 :(得分:1)

您可以尝试这样:

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

答案 2 :(得分:0)

要执行所需的操作,需要遍历字典列表以查找匹配的字典(如果有)。

这是一种蛮力(通过线性搜索)的方式:

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