1

I have a txt file and I want to read values into a dictionary. Different from common dictionary, the value of each key is a value pair, for example:

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? 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.

2
  • 1
    Can you show the actual dictionary structure you want, rather than this strange non-Python pseudocode? Commented May 17, 2016 at 8:09
  • You need to upload what you've done so far. More so, your data structure does not have any dictionary. Is this what you intend: {'tiger': [{'eat': 'meat'}, {'eat': 'people'}]}? Commented May 17, 2016 at 8:12

5 Answers 5

3
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]})
Sign up to request clarification or add additional context in comments.

Comments

1

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

{'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

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)

Comments

1

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

Comments

0

Once, you have read the lines from the file, you can create a nested defaultdict for this purpose:

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:

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:

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.