Why can't python properly define the variable - python

So I've been stuck wondering why I keep getting a key error, I defined the variables needed (items to store the list of key in the dictionary 'a' (Salad, soup, canapes)) and the dictionary is properly setup. I've managed to narrow it down to the fact that it defines items as the list of keys for the dictionary a, but is unable to use it outside of the .join function I used. Why am I getting a key error for items?
Any and all help is appreciated.
#Dictionaries#
a = {'SALAD': {'CAPRESE SALAD': 15, 'CEASAR SALAD BITE': 15, 'EGG SALAD': 15},
'SOUP': {'PUMPKIN COCONUT SOUP': 15, 'TOMATO SOUP': 15, 'CREAMY BROCCOLI SOUP': 15},
'CANAPES': {'BACON DEVILLED EGGS': 15, 'HALLOUMI DIPPERS': 15, 'MINI PARMA HAM VEGGIE TARTS': 15}}
#obtaining the key from the dictionary 'a'#
class keyretrieval:
def __init__(self, v, meal):
#setting up title for dialog box#
title = meal.capitalize()
items = getList(v)
inp = simpledialog.askstring(title, 'what would you like for your ' + meal + '?\nwe have ' + ', '.join(items))
#matching user casing to dictionary casing#
inp = inp.upper()
#other class used that I didn't copy onto here#
key = Menucheckkey(inp, items)
self.choice = key
#getting a key from a, appetizer is only used for the dialog box#
akey = keyretrieval(a, 'appetizer')

theres no "appetizer" key in the 'a' dictionary
If you want your code to insert a new key when an object is initialized, you can try adding the following to your init function
v.update({title : items})

Related

parse str into valid json python

im given the following input:
'family': 'man: name, woman: name, child: name , grandma: name, grandpa: name'
where 'family' is a key, and its value is a bunch of other key-value pairs. as you can tell, you cant parse it using json() because this string is not structured in json format. ive been trying for hours to parse this string into a dictionary/json valid string so i could work with it properly and change name values accordingly. would appreciate the help.
Assuming that no key and no value ever contains a comma or a colon, you could do this:
def split_to_dict(string: str) -> dict[str, str]:
output = {}
for pair in string.split(','):
key, value = pair.split(':')
output[key.strip()] = value.strip()
return output
Calling it like this:
s = 'man: name, woman: name, child: name , grandma: name, grandpa: name'
d = split_to_dict(s)
print(d)
gives the following:
{'man': 'name', 'woman': 'name', 'child': 'name', 'grandma': 'name', 'grandpa': 'name'}
For readability purposes, I would refrain from doing this in a dictionary comprehension.
You first need to convert it to a correct json.
d = {'family': 'man: name, woman: name, child: name , grandma: name, grandpa: name'}
d['family'] = re.sub("(\w+)", r'"\1"', d['family'])
# now parse it
json.loads("{" + d['family'] + "}")
Assuming the input is loaded in as a dictionary and we want to turn the value of family into a corresponding dictionary of key-value pairs. We can do that by doing some string processing as such:
>>> d = {'family': 'man: name, woman: name, child: name , grandma: name, grandpa: name'}
>>> d['family'] = { x.split(':')[0] : x.split(':')[1].strip() for x in d['family'].split(', ')}
>>>
>>> d['family']
>>> {'man': 'name','woman': 'name', 'child': 'name', 'grandma': 'name', 'grandpa': 'name'}
We first split the value of family into key-value strings, and then we further split each key-value string to turn it into the corresponding key-value pair in the list comprehension of the new dictionary.

I have an input file that I am trying to build a dictionary from

I have an input file that I am trying to build a data base from.
Each line looks like this:
Amy Shchumer, Trainwreck, I Feel Pretty, Snatched, Inside Amy Shchumer
Bill Hader,Inside Out, Trainwreck, Tropic Thunder
And so on.
The first string is an actor\actress, and then movies they played in.
The data isn't sorted and they are some trailing whitespaces.
I would like to create a dictionary that would look like this:
{'Trainwreck': {'Amy Shchumer', 'Bill Hader'}}
The key would be the movie, the values should be the actors in it, unified in a set data type.
def create_db():
my_dict = {}
raw_data = open('database.txt','r+')
for line in raw_data:
lst1 = line.split(",") //to split by the commas
len_row = len(lst1)
lst2 = list(lst1)
for j in range(1,len_row):
my_dict[lst2[j]] = set([lst2[0]])
print(my_dict)
It doesn't work... it doesn't solve the issue that when a key already exists then the actor should be unified in a set with the prev actor
Instead I end up with:
'Trainwreck': {'Amy Shchumer'}, 'Inside Out': {'Bill Hader'}
def create_db():
db = {}
with open("database.txt") as data:
for line in data.readlines():
person, *movies = line.split(",")
for m in movies:
m = m.strip()
db[m] = db.get(m, []) + [person]
return db
Output:
{'Trainwreck': ['Amy Shchumer', 'Bill Hader'],
'I Feel Pretty': ['Amy Shchumer'],
'Snatched': ['Amy Shchumer'],
'Inside Amy Shchumer': ['Amy Shchumer'],
'Inside Out': ['Bill Hader'],
'Tropic Thunder': ['Bill Hader']}
This will loop through the data and assign the first value of each line to person and the rest to movies (see here for an example of how * unpacks tuples). Then for all the movies, it uses .get to check if it’s in the database yet, returning the list if it is and an empty list if it isn’t. Then it adds the new actor to the list.
Another way to do this would be to use a defaultdict:
from collections import defaultdict
def create_db():
db = defaultdict(lambda: [])
with open("database.txt") as data:
for line in data.readlines():
person, *movies = line.split(",")
for m in movies:
db[m.strip()].append(person)
return db
which automatically assigns [] if the key does not exist.

Split string, unicode, unicode, string in python

I was trying to split combination of string, unicode in python. The split has to be made on the ResultSet object retrieved from web-site. Using the code below, I am able to get the details, actually it is user details:
from bs4 import BeautifulSoup
import urllib2
import re
url = "http://www.mouthshut.com/vinay_beriwal"
profile_user = urllib2.urlopen(url)
profile_soup = BeautifulSoup(profile_user.read())
usr_dtls = profile_soup.find("div",id=re.compile("_divAboutMe")).find_all('p')
for dt in usr_dtls:
usr_dtls = " ".join(dt.text.split())
print(usr_dtls)
The output is as below:
i love yellow..
Name: Vinay Beriwal
Age: 39 years
Hometown: New Delhi, India
Country: India
Member since: Feb 11, 2016
What I need is to create distinct 5 variables as Name, Age, Hometown, Country, Member since and store the corresponding value after ':' for same.
Thanks
You can use a dictionary to store name-value pairs.For example -
my_dict = {"Name":"Vinay","Age":21}
In my_dict, Name and Age are the keys of the dictionary, you can access values like this -
print (my_dict["Name"]) #This will print Vinay
Also, it's nice and better to use complete words for variable names.
results = profile_soup.find("div",id=re.compile("_divAboutMe")).find_all('p')
user_data={} #dictionary initialization
for result in results:
result = " ".join(result.text.split())
try:
var,value = result.strip().split(':')
user_data[var.strip()]=value.strip()
except:
pass
#If you print the user_data now
print (user_data)
'''
This is what it'll print
{'Age': ' 39 years', 'Country': ' India', 'Hometown': 'New Delhi, India', 'Name': 'Vinay Beriwal', 'Member since': 'Feb 11, 2016'}
'''
You can use a dictionary to store your data:
my_dict = {}
for dt in usr_dtls:
item = " ".join(dt.text.split())
try:
if ':' in item:
k, v = item.split(':')
my_dict[k.strip()] = v.strip()
except:
pass
Note: You should not use usr_dtls inside your for loop, because that's would override your original usr_dtls

Save dictionary to model object

I have a dictionary like this one:
{'company_name': 'Google', 'title': 'headline', ...}
I know that i can store the values using this way:
user = User(company_name=data_db_form['company_name'], title=data_db_form['title']...)
However this is not good if I have many form fields.
There is any way to do this without hard code all the maps? The key value of the dictionary is the same of his model.
You can use the following:
user = User(**data_db_form)
Here is the full example:
class User():
def __init__(self, company_name='unknown', title='unknown'):
self.company_name = company_name
self.title = title
data_db_form = {'company_name': 'Google', 'title': 'headline'}
user = User(**data_db_form)
print user.company_name # prints Google
print user.title # prints headline
Loop over the dictionary using for key, value in dic.iteritems():, then in each iteration you have company_name, title, etc. in key and Google, headline, etc. in value.

Python: change value inside dual key dictionary

So what I'm trying to do is make a dictionary of people and their information but I want to use their names as the main key and have each part of their information to also have a key. I have not been able to figure out how to go about changing the values of their individual information.
I'm not even sure if I'm going about this the right way here is the code.
name = raw_input("name")
age = raw_input("age")
address = raw_input("address")
ramrod = {}
ramrod[name] = {'age': age}, {'address' : address}
print ramrod
#prints out something like this: {'Todd': ({'age': '67'}, {'address': '55555 FooBar rd'})}
What you are looking for is a simple nested dictionary:
>>> data = {"Bob": {"Age": 20, "Hobby": "Surfing"}}
>>> data["Bob"]["Age"]
20
A dictionary is not a pair - you can store more than one item in a dictionary. So you want one dictionary containing a mapping from name to information, where information is a dictionary containing mappings from the name of the information you want to store about the person to that information.
Note that if you have behaviour associated with the data, or you end up with a lot of large dictionaries, a class might be more suitable:
class Person:
def __init__(self, name, age, hobby):
self.name = name
self.age = age
self.hobby = hobby
>>> data = {"Bob": Person("Bob", 20, "Surfing")}
>>> data["Bob"].age
20
You were close
ramrod[name] = {'age': age, 'address' : address}

Categories