Creating a dictionary with list of lists in Python

前端 未结 3 1878
夕颜
夕颜 2020-12-01 18:32

I have a huge file (with around 200k inputs). The inputs are in the form:

A B C D
B E F
C A B D
D  

I am reading this file and storing it i

3条回答
  •  广开言路
    2020-12-01 18:44

    The accepted answer is correct, except that it reads the entire file into memory (may not be desirable if you have a large file), and it will overwrite duplicate keys.

    An alternate approach using defaultdict, which is available from Python 2.4 solves this:

    from collections import defaultdict
    d = defaultdict(list)
    with open('/tmp/spam.txt') as f:
      for line in f:
        parts = line.strip().split()
        d[parts[0]] += parts[1:]
    

    Input:

    A B C D
    B E F
    C A B D
    D  
    C H I J
    

    Result:

    >>> d = defaultdict(list)
    >>> with open('/tmp/spam.txt') as f:
    ...    for line in f:
    ...      parts = line.strip().split()
    ...      d[parts[0]] += parts[1:]
    ...
    >>> d['C']
    ['A', 'B', 'D', 'H', 'I', 'J']
    

提交回复
热议问题