Building Nested dictionary in Python reading in line by line from file

后端 未结 2 1828
清酒与你
清酒与你 2021-01-16 11:24

The way I go about nested dictionary is this:

dicty = dict()
tmp = dict()
tmp[\"a\"] = 1
tmp[\"b\"] = 2
dicty[\"A\"] = tmp

dicty == {\"A\" : {\"a\" : 1, \"b         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-16 12:07

    Use a collections.defaultdict() object to auto-instantiate nested dictionaries:

    from collections import defaultdict
    
    def doubleDict(filename):
        dicty = defaultdict(dict)
        with open(filename, "r") as f:
            for i, line in enumerate(f):
                outer, inner, value = line.split()
                dicty[outer][inner] = value
                if i % 25 == 0:
                    print(dicty)
                    break #print(row)
        return(dicty)
    

    I used enumerate() to generate the line count here; much simpler than keeping a separate counter going.

    Even without a defaultdict, you can let the outer dictionary keep the reference to the nested dictionary, and retrieve it again by using values[0]; there is no need to keep the temp reference around:

    >>> dicty = {}
    >>> dicty['A'] = {}
    >>> dicty['A']['a'] = 1
    >>> dicty['A']['b'] = 2
    >>> dicty
    {'A': {'a': 1, 'b': 1}}
    

    All the defaultdict then does is keep us from having to test if we already created that nested dictionary. Instead of:

    if outer not in dicty:
        dicty[outer] = {}
    dicty[outer][inner] = value
    

    we simply omit the if test as defaultdict will create a new dictionary for us if the key was not yet present.

提交回复
热议问题