附加到Python中的嵌套列表或字典

问题描述:

我经常通过逐行读取文件来填充列表和字典.

I often find myself populating lists and dicts by reading in files line by line.

比方说,我正在阅读人们和他们最喜欢的食物的清单:

Let's say I'm reading in a list of people and their favourite foods:

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

到Python字典:

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

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

The general pattern I use is to read the file line by line, in each case checking if the key exists already before attempting to append. Today I decided to generalise this and write a safe_append function which would create the relevant object before appending to a list or setting a dictionary key:

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方式来做到这一点?

This seems rather clumsy and ugly. My question: Is there a better/more pythonic way to do this?

更好的方法是使用defaultdict:

The better way is to use a defaultdict:

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