【问题标题】:How can I create Dictionary in Python from file, where values are a list如何在 Python 中从文件创建字典,其中值是一个列表
【发布时间】:2016-09-13 05:17:36
【问题描述】:

我有一个 txt 文件,我想将值读入字典。与普通字典不同,每个key的值是一个值对,例如:

tiger eat meat
tiger eat people
rabbit eat carrot
people can walk
trees has root
people has hand

我想要一本字典,

tiger, {eat, meat}, {eat, people}
rabbit, {eat, carrot}
trees, {has, root}
people, {can, walk}, {has, hand}

我应该只将read linessplit(\n) 分成 3 个项目并将第一个作为键存储,其余两个作为值存储吗?还是有更好的方法来存储这两个值?

我的目标是,当我查询老虎吃什么时,我想得到答案meatpeople

【问题讨论】:

  • 你能显示你想要的实际字典结构,而不是这个奇怪的非 Python 伪代码吗?
  • 你需要上传你到目前为止所做的事情。更重要的是,您的数据结构没有任何字典。这是你想要的:{'tiger': [{'eat': 'meat'}, {'eat': 'people'}]}

标签: python dictionary


【解决方案1】:

创建一个字典,其键是主题,其值是一个列表,其中包含以动词为键、对象为值的字典(见结果)。

animal_attr = {} #Don't mind the name :)
with open (filename,"r") as f:
    for line in f:
        items = line.split()
        if items[0] not in animal_attr.keys():
            animal_attr[items[0]] = []            
        animal_attr[items[0]].append({items[1]: items[2]})

print(animal_attr)
#{'tiger': [{'eat': 'meat'}, {'eat': 'people'}], 'trees': [{'has': 'root'}],
# 'rabbit': [{'eat': 'carrot'}], 'people': [{'can': 'walk'}, {'has': 'hand'}]}

【讨论】:

    【解决方案2】:
    import collections
    
    lines=[]
    with open('data1', 'r') as f:
        lines=list(map(lambda line:line.strip(), f.readlines()))
    
    d, flag=collections.defaultdict(list), False
    for line in lines:
        temp=list(map(lambda x:x.strip(), line.split()))
        d[temp[0]].append(temp[1:])
    print(d)
    

    这是输出:

    $ cat data1
    tiger eat meat
    tiger eat people
    rabbit eat carrot
    people can walk
    trees has root
    people has hand
    $ python3 a.py 
    defaultdict(<class 'list'>, {'rabbit': [['eat', 'carrot']], 'trees': [['has', 'root']], 'tiger': [['eat', 'meat'], ['eat', 'people']], 'people': [['can', 'walk'], ['has', 'hand']]})
    

    如果你想要这个结构:

    $ python3 a.py 
    defaultdict(<class 'list'>, {'people': [{'can': 'walk'}, {'has': 'hand'}], 'tiger': [{'eat': 'meat'}, {'eat': 'people'}], 'trees': [{'has': 'root'}], 'rabbit': [{'eat': 'carrot'}]})
    

    将脚本中的倒数第二行替换为:

    d[temp[0]].append({temp[1]:temp[2]})
    

    【讨论】:

      【解决方案3】:
      import collections
      
      d=collections.defaultdict(list)
      with open('text.txt', 'r') as lines:
          for line in lines:
              temp=line.split()
              d[temp[0]].append({temp[1]: temp[2]})
      print(d)
      

      输出:

      defaultdict(<type 'list'>, {'tiger': [{'eat': 'meat'}, {'eat': 'people'}], 'trees': [{'has': 'root'}], 'rabbit': [{'eat': 'carrot'}], 'people': [{'can': 'walk'}, {'has': 'hand'}]})
      

      【讨论】:

        【解决方案4】:

        首先,你可以根据主语和动词来积累数据,像这样

        data = {}
        with open("Input.txt") as fin:
            for line in fin:
                subject, verb, obj = line.strip().split()
                data.setdefault(subject, {}).setdefault(verb, []).append(obj)
        

        现在,data 将如下所示

        {'people': {'can': ['walk'], 'has': ['hand']},
         'rabbit': {'eat': ['carrot']},
         'tiger': {'eat': ['meat', 'people']},
         'trees': {'has': ['root']}}
        

        我们基本上已经创建了将值作为列表的嵌套字典。

        现在,只需以您喜欢的方式迭代和打印结果即可

        for subject in data:
            print subject,
            for verb in data[subject]:
                for obj in data[subject][verb]:
                    print "{{{}, {}}}".format(verb, obj),
            print
        

        输出

        tiger {eat, meat} {eat, people}
        trees {has, root}
        rabbit {eat, carrot}
        people {has, hand} {can, walk}
        

        注意:如果数据的原始顺序很重要,那么可以使用collections.OrderedDict代替普通字典,像这样

        from collections import OrderedDict
        
        
        data = OrderedDict()
        with open("Input.txt") as fin:
            for line in fin:
                subject, verb, obj = line.strip().split()
                data.setdefault(subject, OrderedDict()).setdefault(verb, []).append(obj)
        

        【讨论】:

          【解决方案5】:

          一旦您从文件中读取了这些行,您就可以为此创建一个nested defaultdict

          d = defaultdict(lambda: defaultdict(list))
          
          for line in lines:
              words = line.split()
              d[words[0]][words[1]].append(words[2])
          

          如果您print(d),您将获得以下信息:

          defaultdict(<function <lambda> at 0x7fa858444320>, {'tiger': defaultdict(<type 'list'>, {'eat': ['meat', 'people'], 'eats': []}), 'trees': defaultdict(<type 'list'>, {'has': ['root']}), 'rabbit': defaultdict(<type 'list'>, {'eat': ['carrot']}), 'people': defaultdict(<type 'list'>, {'has': ['hand'], 'can': ['walk']})})
          

          而且,您可以通过以下方式访问老虎吃什么:

          >>> d['tiger']['eat']
          ['meat', 'people']
          

          如果你想看看people 能做什么:

          >>> d['people']['can']
          ['walk']
          

          【讨论】:

            猜你喜欢
            • 2020-07-29
            • 2021-07-12
            • 2018-12-21
            • 1970-01-01
            • 2020-09-18
            • 2021-12-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多