0

so sorry for my question if it seems so easy but I am newbie user of python and I can not find a way to solve it.

I have a "dish.py" file which includes some sub-lists

Fruits={"Ap":Apple
        "Br":Black Mulberry
        "Ch":Black Cherry
        }
Meals={"BN":Bean
        "MT":Meat
        "VG":Vegetable
        }
Legumes={"LN":Green Lentil
        "P": Pea
        "PN":Runner Peanut
        }

I want to impelement the dish.py file in a code that at the end, I want to create a query inside of the file

with open("/home/user/Py_tut/Cond/dish.py", 'r') as dish:
           content = dish.read()
print dish.closed
dm=dict([dish])
nl=[x for x in dm if x[0]=='P']
for x in dm:
    x=str(raw_input("Enter word:"))
   if x in dm:
        print dm[x]
    elif x[0]==("P"):
        nl.append(x)
        print .join( nl)

It may be look so messy but

  1. dm=dict([dish]) I want to create a dictionary for query
  2. nl=[x for x in dm if x[0]=='P'] I want to write words begin with "P" letter

Here is my questions:

1. Q: I suppose there is a problem with my dish.py file. How can I reorganize it?

2. Q: How can I apply a query to the file and extract the words begin with "P" Thank you so much in advance

2
  • 1
    Any reason why are you reading your dish.py file in memory instead of letting the Python interpreter parse it for you? (well, except that the defined dict is written in bad syntax, but then why are you calling it dish.py when it's not supposed to be a Python file?) Commented Jun 4, 2017 at 19:44
  • I simply don't know how and that's why I've written it a very bad shape. I start from scratch to understand how to parse and etc. thanks anyway for your comment Commented Jun 5, 2017 at 21:05

2 Answers 2

1

dict() can't load strings:

>>> dict("{'a': 1, 'b': 2}")
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
  dict("{'a': 1, 'b': 2}")
ValueError: dictionary update sequence element 0 has length 1; 2 is required

As a sequence it would be ("{", "'", "a", "'", ":",...

Instead I would use the json module, change the dish.py format (changing extension to .json and using JSON syntax) and change the code.

dish.json

{
  "Fruits": {
     "Ap": "Apple",
     "Br": "Black Mulberry",
     "Ch": "Black Cherry"
  },
  "Meals": {
     "BN": "Bean",
     "MT": "Meat",
     "VG": "Vegetable"
  },
  "Legumes": {
     "GL": "Green Lentin",
     "P": "Pea",
     "PN": "Running Peanut"
  }
}

__init__.py

import json
with open("/home/user/Py_tut/Cond/dish.py", 'r') as dish:
    content = dish.read()
print(dish.closed)
dm = json.loads(content) # loads JSON
nl=[x for x in dm if x[0]=='P']
for x in dm:
    x = str(raw_input("Enter word:"))
    if x in dm:
        print dm[x]
    elif x[0] == ("P"):
        nl.append(x)
        print "".join(nl)
  1. Q: How can I apply a query to the file and extract the words begin with "P" Thank you so much in advance

Assuming that you want to get every string separated by either space or newline and return them into a list, i'd do this:

import re #Importing RegExp module

def wordsBeginP():
  with open("words.txt") as wordsfile: # Querying a file
    words = wordsfile.open

  parsed = re.sub(r"\n", " ", words) # Replace \n to " "
  return [for i in parsed.split(" ") if i[0] == "P"] # Return list of words
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much correcting my list. I try to import json, probably because of lack of knowledge, I have some issues but these give me a point to where should go while writing script. Your solution for query also great, it enlightens me. Thanks for your valuable contributions.
1

So I think you have more than these two issues/questions. First, if you want to include 'hardcoded' lists, dicts and such, you probably want to include dish with dish.py being in your working directory.

That is, if your data structures in the python file are actually in the correct form:

Fruits={"Ap":'Apple',
        "Br":'Black Mulberry',
        "Ch":'Black Cherry'
        }
Meals={"BN":'Bean',
        "MT":'Meat',
        "VG":'Vegetable'
        }
Legumes={"LN":'Green Lentil',
        "P":'Pea',
        "PN":'Runner Peanut'
        }

Finally, you can search in all the datastructures that were named and included in the file, under the created namespace of the include (which is dish).

for f in [dish.Fruits,dish.Meals,dish.Legumes]:
  for k,v in f.items():
    if k.startswith('P'):
      print k,v

Also interesting for you might be pickling (though there are some caveats).

1 Comment

Thank you so much for putting an effort into my messy list. I am a new user and even I were not aware the correct form of the list. That's so great to providing me the correct form. By the way, I try to implement also the second part to my code for search.

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.