【问题标题】:A pythonic way to append new values to a dict?一种将新值附加到字典的pythonic方法?
【发布时间】:2021-11-30 10:24:30
【问题描述】:

让我们考虑一下:

x = [1, 2, 3, 4, 5, 6, 7]

然后,我们创建一个字典:

vnf_dict = dict([(key, [None]) for key in (x)])

这给了我们:

vnf_dict: {1: [None], 2: [None], 3: [None], 4: [None], 5: [None], 6: [None], 7: [None]}

现在我使用以下函数更新每个键的值,之前删除“无”以防万一。

def add_value(value, dictionary):
    if None in dictionary[value]:
        dictionary[value] = []
        dictionary[value].append(['Hello'])
    else:
        dictionary[value].append(['By'])
    return dictionary

因此获得:

print(add_value(1, vnf_dict))
print(add_value(1, vnf_dict))


vnf_dict: {1: [['Hello']], 2: [None], 3: [None], 4: [None], 5: [None], 6: [None], 7: [None]}
vnf_dict: {1: [['Hello'], ['By']], 2: [None], 3: [None], 4: [None], 5: [None], 6: [None], 7: [None]}

是否有更快/Pythonic 的方式来实现上述所有功能?

【问题讨论】:

    标签: python-3.x dictionary


    【解决方案1】:

    是的。

    >>> from collections import defaultdict
    >>> vnf = defaultdict(list)
    >>> vnf[1].append(["Hello"])
    >>> vnf[1].append(["Bye"])
    >>> vnf[0].append(["Greetings"])
    >>> vnf
    defaultdict(list, {1: [['Hello'], ['Bye']], 0: [['Greetings']]})
    

    【讨论】:

    • 字典键需要从外部列表创建。字典值需要初始化为“无”。最后,当第一次添加一个值时,必须删除它的实际值'None'。
    • @krm76 如果你这么严格地坚持最初的设计,我很难找到任何 Pythonic 的东西,因为这对我来说听起来非常不合 Python。
    猜你喜欢
    • 1970-01-01
    • 2017-05-28
    • 1970-01-01
    • 2023-03-23
    • 2016-12-30
    • 1970-01-01
    • 1970-01-01
    • 2019-08-16
    相关资源
    最近更新 更多