python - 在 Python 中附加到嵌套列表或字典

标签 python list dictionary

我经常发现自己通过逐行读取文件来填充列表和字典。

假设我正在阅读一个人和他们最喜欢的食物的列表:

ANNE      CHEESE  
ANNE      POTATO 
JOE       PEAS    
JOE       CHIPS   
JOE       FISH
BERNARD   LENTILS

到 Python 字典:

{
 "ANNE"   : ["CHEESE", "POTATO"], 
 "JOE"    : ["PEAS",   "CHIPS",   "FISH"],
 "BERNARD": ["LENTILS"]
}

我使用的一般模式是逐行读取文件,在每种情况下,在尝试追加之前检查 key 是否已经存在。今天我决定概括这一点并编写一个 safe_append 函数,该函数将在附加到列表或设置字典键之前创建相关对象:

def safe_append(list_object, list_key, list_value, value_dict_key= None):
    # Add empty dict if it does not already exist
    if list_key not in list_object:
        if value_dict_key is not None:
            list_object[list_key] = {}
        else: 
            list_object[list_key] = []
    # Append/set value
    if value_dict_key is not None:
        list_object[list_key][value_dict_key] = list_value
    else: 
        list_object[list_key].append(list_value)
    # Return object (for chaining)
    return list_object 

# Usage: dict in dict
x = {}
safe_append(x, "a","b",value_dict_key = "c")
>>> {"a":{"c":"b"}}
# Usage: list in dict
x = []
safe_append(x, "a","b")
>>> {"a":["b"]}

这看起来相当笨拙和丑陋。我的问题:是否有更好/更 pythonic 的方法来做到这一点?

最佳答案

更好的方法是使用默认字典:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d["hello"].append(1)
>>> d["hello"].append(2)
>>> dict(d)
{'hello':[1, 2]}

关于python - 在 Python 中附加到嵌套列表或字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25364449/

相关文章:

当我尝试对具有相同代码的对象的值求和时,出现 java.util.ConcurrentModificationException

r - 将数据框列表的名称的数字部分添加为列

python - 将包含转义字符的字符串转换为字典

python - 在另一台计算机上运行时,运行绑定(bind) SWIG 的 Python+C 程序会出现缺少 DLL 错误

python - python中如何根据需求生成JWT

python - 使用 BeautifulSoup 从网页中抓取的 URL

python - 如何选择深度嵌套的键 :values from dictionary in python

python - 打印格式合理的列表

带条件求和的Python代码

python - 在Python中的世界地图上覆盖数组