简体   繁体   English

如何从文件(其中值是列表)在Python中创建字典

[英]How can I create Dictionary in Python from file, where values are a list

I have a txt file and I want to read values into a dictionary. 我有一个txt文件,我想将值读入字典。 Different from common dictionary, the value of each key is a value pair, for example: 与普通字典不同,每个key的值是一个值对,例如:

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

I want to get a dictionary that, 我想要一本字典,

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

Should I just read lines , split(\\n) into 3 items and store the first one as the key and the rest two ones as the values? 我应该只read linessplit(\\n)分为3个项目,并将第一个存储为键,将其余两个存储为值吗? Or there is a better way to store the two values? 还是有更好的方法来存储两个值?

My objective is that, when I query what does a tiger eat, I want to get the answer meat and people . 我的目标是,当我查询老虎吃什么时,我想得到答案meatpeople

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)

Here is the output: 这是输出:

$ 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']]})

And if you want this structure: 如果您想要这种结构:

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

replace the 2nd last line in the script to: 将脚本中的第二行替换为:

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

First, you can accumulate the data, based on the subjects and the verbs, like this 首先,您可以像这样基于主语和动词来累积数据

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

Now, data will look like this 现在, data将如下所示

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

we basically have created nested dictionaries with the values as lists. 我们基本上已经创建了嵌套字典,其值作为列表。

Now, its just a simple matter of iterating and printing the result, in the manner you like 现在,只需按照您喜欢的方式迭代和打印结果即可

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

Output 输出量

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

Note: If the original order of the data is important, then instead of using normal dictionaries, you can use collections.OrderedDict , like this 注意:如果数据的原始顺序很重要,则可以使用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)

Create a dictionary whose keys are the subjects and whose values is a list containing dictionaries with verbs as keys and objects as values (see results). 创建一个字典,其键为主题,其值为包含字典的列表,其中动词为键,对象为值(请参见结果)。

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'}]}

Once, you have read the lines from the file, you can create a nested defaultdict for this purpose: 一旦您从文件中读取了行,就可以为此目的创建一个嵌套的defaultdict

d = defaultdict(lambda: defaultdict(list))

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

If you print(d) you will get following: 如果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']})})

And, you can access what tiger eats as following: 而且,您可以按以下方式访问老虎所吃的食物:

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

If, you want to see what all can a people do: 如果要查看people全部能力,请执行以下操作:

>>> d['people']['can']
['walk']
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)

Output: 输出:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从无序列表创建字典,其中列表包含键,然后是多个值? - How can I create a dictionary from an unordered list, where the list contains the keys which are then followed by multiple values? 我如何从一个列表中创建一个字典,其中键是索引,值是列表的一个一个的实际元素? - How can I create a dictionary from a list where the keys are the indexes and the values are the actual elements of the list one by one? 如何从另一个python字典中的一个字典中获得相应的列表值,在列表中它们被列为键,比较并打印出csv? - How can I get corresponding list values in one dictionary from another python dictionary where they are listed as keys, compare and print out a csv? 如何使用正在读取的文本文件中的值创建python字典 - How can I create a python dictionary using values from a text file that I'm reading in 如何从值列表的字典中创建字典列表? - how can i make a list of dictionary from the dictionary where values are a list? 如何创建具有 2 个键的字典,其中第一个键是索引,第二个键来自列表,值来自 df 的列? - How can I create a dictionary with 2 keys where the the first key is the index, the second key is from a list and the values from columns of a df? 如何从txt文件在python中创建字典? - How can I create a dictionary in python from a txt file? 如何为列表中的一个键创建具有多个值的 Python 字典,然后创建具有一列和多行的 pandas 数据框 - How can I create a Python dictionary with multiple values for one key from a list, to then create a pandas dataframe with one column and multiple rows 如何用Python中的键列表和值字典创建字典? - How to create a dictionary from a list of keys and a dictionary of values in Python? Python 3:列表和字典。 如何创建一个字典来告诉我每个项目来自哪个列表? - Python 3: lists and dictionary. How can I create a dictionary that tells me what list each item is from?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM