1

I'm trying to take a text file with a list in it take the input values and order them in an appropriate output format however I'm having difficulty trying to create a loop and create this dictionary.

I have created a blank dictionary however I'm not sure I'm supposed to create a dictionary like in order to get the output:

foodweb =
{
  “Bird”: [
    Prawn,
    Mussels,
    Crab,
    Limpets,
    Whelk
  ],
  “Crab”: [
    Mussels,
    Limpets
  ],
  “Fish”: [
    Prawn
  ],
  “Limpets”: [
    Seaweed
  ],
  “Lobster”: [
    Crab,
    Mussels,
    Limpets,
    Whelk
  ],
  “Mussels”: [
    Phytoplankton,
    Zooplankton
  ],
  “Prawn”: [
    Zooplankton
  ],
  “Whelk”: [
    Limpets,
    Mussels
  ],
  “Zooplankton”: [
    Phytoplankton
  ]
}

How can I write a loop to make this more simple?!?

file_content = open('AquaticFoodWeb.txt' , 'r')
aquaticfoodweb ={}
for line in file_content:
    myList=line.rstrip('\n').split(" eats ")

This is the list from the txt file

Bird eats Prawn
Bird eats Mussels
Bird eats Crab
Bird eats Limpets
Bird eats Whelk
Crab eats Mussels
Crab eats Limpets
Fish eats Prawn
Limpets eats Seaweed
Lobster eats Crab
Lobster eats Mussels
Lobster eats Limpets
Lobster eats Whelk
Mussels eats Phytoplankton
Mussels eats Zooplankton
Prawn eats Zooplankton
Whelk eats Limpets
Whelk eats Mussels
Zooplankton eats Phytoplankton

This is the desired output format I'm striving for:

Predators and Prey:
Bird eats Prawn, Mussels, Crab, Limpets and Whelk
Crab eats Mussels and Limpets
Fish eats Prawn
Limpets eats Seaweed
Lobster eats Crab, Mussels, Limpets and Whelk
Mussels eats Phytoplankton and Zooplankton
Prawn eats Zooplankton
Whelk eats Limpets and Mussels
Zooplankton eats Phytoplankton

4 Answers 4

1

Hopefully the following will help. You need to start with an empty dictionary. For each line of your input your are correctly splitting out the two parts of your input. You can then use these to create dictionary entries. Each entry in the dictionary will be a list. setdefault is used to allow you to create an empty list when a new animal is found and then append the prey to that list automatically.

Finally, the output requires a bit of thought to ensure items with more than one prey have and added to the output. As dictionaries are not ordered, you will need to sort it before displaying the results:

foodweb = {}

with open('AquaticFoodWeb.txt') as f_input:
    for line in f_input:
        animal, prey = line.strip().split(' eats ')
        foodweb.setdefault(animal, []).append(prey)

print "Predators and Prey:"

for animal, prey in sorted(foodweb.items()):
    if len(prey) > 1:
        print "{} eats {} and {}".format(animal, ", ".join(prey[:-1]), prey[-1])
    else:
        print "{} eats {}".format(animal, ", ".join(prey))

This will give you the following output:

Predators and Prey:
Bird eats Prawn, Mussels, Crab, Limpets and Whelk
Crab eats Mussels and Limpets
Fish eats Prawn
Limpets eats Seaweed
Lobster eats Crab, Mussels, Limpets and Whelk
Mussels eats Phytoplankton and Zooplankton
Prawn eats Zooplankton
Whelk eats Limpets and Mussels
Zooplankton eats Phytoplankton
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much! This worked! However, I don't understand the f_input, what is the purpose of this?!
f_input is just the file input handle. I tend to use 'f_output' for my output file handle name.
Oh, that makes sense now! I thought it was something more complex than that haha! Martin, thank you so much for your help, I really appreciate it!
1

I'm not sure if you are asking for text output or for a dictionary. You can create the dictionary like this:

file_content = open('AquaticFoodWeb.txt' , 'r')
aquaticfoodweb ={}
for line in file_content:
    myList=line.rstrip('\n').split(" eats ")
    try:
        aquaticfoodweb[myList[0]].append(myList[1])
    except KeyError:
        aquaticfoodweb[myList[0]]=[myList[1]]

The try except will create a new entry in the dictionary if it doesn't already exist (making sure that the new entry is a list) and will append to the list if the entry already exists.

1 Comment

Yes, we posted our answers at the same time. I was happy to learn of the default method from you! Would you mind adding a little explaination to your answer? I would have found it useful (I went and looked up the docs instead but someone else coming across it may benefit).
1

like this:

    file_content = open('AquaticFoodWeb.txt' , 'r')
    aquaticfoodweb ={}
    for line in file_content.readlines():
        aquaticfoodweb.setdefault(line.split()[0], []).append(line.split()[-1])
    file_content.close()
    for key, value in aquaticfoodweb.items():
        if len(value) > 1:
            value = value[:-2] + [" and ".join(value[-2:])]
        print "{} eats {}".format(key, ",".join(value))

The setdefault method set dict[key]=default if key is not already in dict.

Comments

0

you can use regular expression maybe? If file is not big it maybe fit

import re

with open('AquaticFoodWeb.txt' , 'r') as f:
   content = f.read()

foodweb = re.findall('(\"(.*?)\").*?\[(.*?)\]') 

for item in foodweb:
   idx = item[1].rfind(", ")
   print "%s eats %s" % (item[0],item[1][0:idx]+item[1][idx:].replace(", ", " and "))

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.