【问题标题】:Create a python dictionary from a tab delimited file that is not 1:1从不是 1:1 的制表符分隔文件创建 python 字典
【发布时间】:2017-07-26 20:07:37
【问题描述】:

我想从一个制表符分隔的文件(无标题)创建两个 python3 字典。该文件有 2 列我想命名为 group_id 和gene_id。一个组可能有多个基因,一个基因可以属于多个组。我会用一个简单的例子来演示我想要什么。

group_id gene_id

A        a
A        b
A        c
A        d
B        a
B        c
B        e

我想要两本词典:

dict1 = {'A':(a,b,c,d),'B':(a,c,e)}

dict2 = {'a':(A,B), 'b':(A), 'c':(A,B), 'd':(A), 'e':(B)}

我想将值存储在元组中以提高速度,因为我的文件是 2.5 GB,我最终会得到稍后必须使用的大字典。

我知道有很多这样的问题,但我无法从那些处理具有键值对的文件中找到答案。

谢谢!

【问题讨论】:

  • 当然。您是否尝试过实现这一点?很高兴看到你的代码,看看你走了多远,遇到了什么困难。
  • Pandas 是一个很好的起点。
  • 值可以是列表而不是元组吗?

标签: python python-3.x dictionary tuples


【解决方案1】:

collections 模块有一个defaultdict 方法,它返回一个新的类字典对象。只需将值附加到每个键即可。

from collections import defaultdict
dict1 = defaultdict(list)
dict2 = defaultdict(list)

with open("C:/path/example.txt") as f:
    header = f.next()
    for line in f:
        if line.strip():
            a,b =  line.strip().split()
            dict1[a].append(b)
            dict2[b].append(a)

print dict1

返回

defaultdict(<type 'list'>, {'A': ['a', 'b', 'c', 'd'], 'B': ['a', 'c', 'e']})

dict2

defaultdict(<type 'list'>, {'a': ['A', 'B'], 'c': ['A', 'B'], 'b': ['A'], 'e': ['B'], 'd': ['A']})

【讨论】:

    【解决方案2】:

    我认为代码在这里不言自明,但基本上由于您使用的是字符串,您可以只拥有两个单独的字典,然后解析每一行。如果您有一个新值,则必须创建一个新条目,您可以使用 if 语句来执行此操作。有一点,您应该使用列表,因为元组是不可变的,并且在创建后无法更改:

    data = """group_id gene_id
        A        a
        A        b
        A        c
        A        d
        B        a
        B        c
        B        e"""
    
    lines = data.splitlines()
    group_dict = {}
    gene_dict = {}
    
    for line in lines[1:]:
        group, gene = line.split()
        if group not in group_dict.keys():
            group_dict[group] = list()
        group_dict[group].append(gene)
    
        if gene not in gene_dict.keys():
            gene_dict[gene] = list()
        gene_dict[gene].append(group)
    
    from pprint import pprint
    pprint(group_dict)
    pprint(gene_dict)
    

    打印:

    {'A': ['a', 'b', 'c', 'd'], 'B': ['a', 'c', 'e']}
    {'a': ['A', 'B'], 'b': ['A'], 'c': ['A', 'B'], 'd': ['A'], 'e': ['B']}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-21
      • 2016-01-05
      相关资源
      最近更新 更多