【问题标题】:How can I make an organized file into dictionary in python3?如何在 python3 中将有组织的文件制作成字典?
【发布时间】:2017-02-17 22:12:52
【问题描述】:

我正在尝试制作这个文件:

c;f
b;d
a;c
c;e
d;g
a;b
e;d
f;g
f;d

变成这样的字典:

{'e': {'d'}, 'a': {'b', 'c'}, 'd': {'g'}, 'b': {'d'}, 'c': {'f', 'e'}, 'f': {'g', 'd'}}.

我现在使用的代码如下:

def read_file(file : open) -> {str:{str}}:
f = file.read().rstrip('\n').split()
answer = {}
for line in f:
    k, v = line.split(';')
    answer[k] = v
return answer

但它给了我{'f': 'g', 'a': 'c', 'b': 'd', 'e': 'd', 'c': 'e', 'd': 'g'}

我该如何解决?

【问题讨论】:

    标签: python string python-3.x dictionary set


    【解决方案1】:

    字典覆盖前一个键,使用defaultdict here

    >>> import collections 
    >>> answer = collections.defaultdict(set)
    >>> for line in f: 
    ...     k, v = line.split(";")
    ...     answer[k].add(v)
    ... 
    >>> answer
    defaultdict(<class 'set'>, {'b': {'d'}, 'd': {'g'}, 'f': {'d', 'g'}, 'e': {'d'}, 'a': {'c', 'b'}, 'c': {'f', 'e'}})
    

    如果您更喜欢传统的方法,那么您可以添加一个if 条件

    >>> answer = {}
    >>> for line in f:
    ...     k,v = line.split(";")
    ...     if k in answer:
    ...         answer[k].add(v)
    ...     else:
    ...         answer[k] = {v}
    ... 
    >>> answer
    {'b': {'d'}, 'd': {'g'}, 'f': {'d', 'g'}, 'e': {'d'}, 'a': {'c', 'b'}, 'c': {'f', 'e'}}
    

    【讨论】:

    • 但是我还有一个问题:dict 类是可散列的,那么为什么我们不只使用默认 dict 来代替所有编码工作呢?看起来默认 dict 更灵活。
    • @ProgrammingDonkey 默认字典在一些用例中更灵活,在其他用例中是普通字典。每当我们不需要默认值,或者当我们没有那个特定的键时抛出错误,我们就不能使用默认字典。因此,有充分的理由认为 dict 比默认 dict 更突出。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    • 2017-04-24
    • 2011-09-27
    • 1970-01-01
    相关资源
    最近更新 更多