Function : Updating & printing a dictionary with the most recent values - python

I've created a function : A dictionary which takes in city name and country name to which the city belongs to. Currently the code just returns a dictionary after each iteration with city name and country name after taking inputs using the input(). I'm trying to update the code (no success so far) so that a new dictionary is printed after each iteration with updated dictionary which returns an output like
{'city' : 'berlin', 'country' : 'germany',
'city' : 'paris', 'country' : 'france',}
The code is as follows :
def city_country(city_name, country_name):
pair = {'City': city_name, 'Country': country_name}
return pair
active = True
while active:
user_city = input("Enter city name : ")
if user_city == 'q':
break
user_country = input("Enter country name : ")
if user_country == 'q':
break
new_pair = city_country(user_city, user_country)
print(new_pair)

The keys of the dictionary type are unique, this way of writing you can always print only one city and one country, maybe you can try to do it in json format, but it means you have to write another function to deal with the duplication of data (directly add or replace)
def city_country(city_name, country_name):
return {'City': city_name, 'Country': country_name}
data = []
while True:
user_city = input("Enter city name : ")
if user_city == 'q':
break
user_country = input("Enter country name : ")
if user_country == 'q':
break
data.append(city_country(user_city, user_country))
print(data)

city_country_dict = {}
active = True
while active:
user_city = input("Enter city name : ")
if user_city == 'q':
break
user_country = input("Enter country name : ")
if user_country == 'q':
break
new_pair = city_country(user_city, user_country)
#=================================
city_country_dict.update(new_pair)
#=================================
print(city_country_dict)

Related

Dictionary Getting Overwritten in While Loop

def get_list_expenses():
expense_list = {}
print('Please type the name of the expense followed by the price of the expense')
while True:
name = input('Name of expense: ')
price = int(input('Price of expense: '))
expense_list.update({
'name': name,
'price': price,
})
cont = input('Want to add another? [y/n] ').lower()
if cont == 'n':
break
print(type(expense_list))
print(expense_list)
return expense_list
Input ==========================
Please type the name of the expense followed by the price of the expense
Name of expense: Food
Price of expense: 100
Want to add another? [y/n] y
Name of expense: Car Insurance
Price of expense: 200
Want to add another? [y/n] n
Output =========================
<class 'dict'>
{'name': 'car', 'price': 200}
I'm new to python and wanted to try and make a budget application to save me time manually inputting information to excel. My idea was to create a loop that would take in the name of an expense and the price per month of it. I wanted to put this into a dictionary so I could .get the information whenever I needed it. However, my dictionary keeps getting overwritten. I've tried a few different solutions I can find online but nothing worked. Thanks in advance.
Using the update method on a dictionary you are basically rewriting the dictionary from scratch at every iteration, for this reason you see a single value at the end (the last one).
I would suggest to create an empty list and then append a new dictionary of values at every iteration:
def get_list_expenses():
expense_list = []
print('Please type the name of the expense followed by the price of the expense')
while True:
name = input('Name of expense: ')
price = int(input('Price of expense: '))
expense_list.append({
'name': name,
'price': price,
})
cont = input('Want to add another? [y/n] ').lower()
if cont == 'n':
break
print(type(expense_list))
print(expense_list)
return expense_list
expense_list.update({
'name': name,
'price': price,
})
Should be:
expense_list.update({name,price})
Dictionary is a key value pair. In your case key will be 'Name of expense' and value will be price. The way you are creating you have 2 keys in dictionary. 1st key is 'name' and second key is 'price'.
You can simply do:
expense_list[name] = price
If name exists it will update otherwise will add.
Make expense_list an actual list:
expense_list = []
and then append to it
expense_list.append({
'name': name,
'price': price,
})

I need help on how to save dictionary elements into a csv file

I intend to save a contact list with name and phone number in a .csv file from user input through a dictionary.
The problem is that only the name is saved on the .csv file and the number is omitted.
contacts={}
def phone_book():
running=True
while running:
command=input('A(dd D)elete L)ook up Q)uit: ')
if command=='A' or command=='a':
name=input('Enter new name: ')
print('Enter new number for', name, end=':' )
number=input()
contacts[name]=number
elif command=='D' or command=='d':
name= input('Enter the name to delete: ')
del contacts[name]
elif command=='L' or command=='l':
name= input('Enter name to search: ')
if name in contacts:
print(name, contacts[name])
else:
print("The name is not in the phone book, use A or a to save")
elif command=='Q' or command=='q':
running= False
elif command =='list':
for k,v in contacts.items():
print(k,v)
else:
print(command, 'is not a valid command')
def contact_saver():
import csv
global name
csv_columns=['Name', 'Phone number']
r=[contacts]
with open(r'C:\Users\Rigelsolutions\Documents\numbersaver.csv', 'w') as f:
dict_writer=csv.writer(f)
dict_writer.writerow(csv_columns)
for data in r:
dict_writer.writerow(data)
phone_book()
contact_saver()
as I am reading your code contacts will look like
{
'name1': '1',
'name2': '2'
}
keys are the names and the value is the number.
but when you did r = [contacts] and iterating over r for data in r that will mess up I guess your code since you are passing dictionary value to writerow instead of a list [name, number]
You can do two things here. parse properly the contacts by:
for k, v in contacts.items():
dict_writer.writerow([k, v])
Or properly construct the contacts into a list with dictionaries inside
[{
'name': 'name1',
'number': 1
}]
so you can create DictWriter
fieldnames = ['name', 'number']
writer = csv.DictWriter(f, fieldnames=fieldnames)
...
# then you can insert by
for contact in contacts:
writer.writerow(contact) # which should look like writer.writerow({'name': 'name1', 'number': 1})

How to check if User Input is present in CSV Python

I am trying create a program that will ask for user input for a city and gender and Test their input to make sure it is valid and corresponds to values within the a CSV that has city name and different gender population.
How do I check if the userinput for both gender and city name are within the csv file. I want to create it in the way that the if the user does not put a valid year or gender. it will tell the user to choose a different city and or year.
Here is what the CSV looks like:
name,gen_male,gen_female
Tokyo,5000,4500
San_Francsico,400,500
Manila,600,700
New_York,8000,9000
Paris,5600,5600
Chicago,500,6000
Can anyone help me to figure out a way to check user input if a given value is within the csv file.
Here is my script:
import csv
with open('C:/Users/PycharmProjects/CityGen.csv') as csvfile:
reader = csv.DictReader(csvfile)
city = raw_input('Which city?:')
gender = raw_input('What gender?:')
yearPop = 'gen_' + year
try:
for row in reader:
if row['name'] == city:
print row[yearPop]
except ValueError:
print 'incorrect value'
I would first read the csv file and save it into a dictionary with the city name as key and the value is a tuple (or maybe a named tuple?) tuple[0] is gen_male, and tuple[1] is gen_female. Then ask the user to input city's name, look it up in the dictionary, if its there, then ask him to input the gender and check if its valid for that city.
with open('C:/Users/PycharmProjects/CityGen.csv') as csvfile:
reader = csv.DictReader(csvfile)
dictionary = {}
for row in reader:
city = row[0]
genders = tuple(row[1:])
dict1 = {city: genders}
dictionary.update(dict1)
city = raw_input('Which city?:')
if city in dictionary:
gender = raw_input('What gender?:')
if gender in dictionary[city]:
# gender and city are valid
else:
# gender is not valid
else:
# city is not valid

python dictionary - how to search and display answers

I'm trying to use a database implemented as a dictionary to search for a user entered value and if that value is found, it is displayed or else an error message is displayed.
'uuc' or 'uum' etc refers to abbreviations for a university campus.
The user should be able to enter one of the above values and any matches should be displayed. However, this doesn't work in my code and I can't locate the problem.
def all_from(datab,university):
l = len(datab)
k = 1
i = 0
while k <= 1:
s = datab[k]
the_university = s[2]
if university == the_university:
i = i + 1
print datab[k]
k = k + 1
if i == 0:
print 'Nobody goes to University there!'
datab = dict()
datab[1] = ['walker','matthew','uuc',1]
datab[2] = ['stewart','rory','uum',2]
datab[3] = ['toner','kevin','qub',4]
datab[4] = ['hughes','johnny','uuj',1]
datab[5] = ['douglas','kenny','uuc', 3]
datab[6] = ['hooks', 'peter','qub',1]
datab[7] = ['campbell','vicky','uuj',2]
datab[8] = ['crooks','laura','uum',4]
datab[9] = ['irwin','emma','uuc',3]
datab[10] = ['patterson','steve','uuc',1]
university = (raw_input('Enter the University here: '))
all_from(datab,university)
My contribution. I feel that arranging the students as items in a list, with the different fields as dictionary keys is a better data structure.
def find_all(datab,uni):
for student in datab:
if student['uni'] == uni:
print(student)
datab = []
datab.append( {'lastname':'walker', 'firstname':'matthew','uni':'uuc','year':1})
datab.append( {'lastname':'stewart','firstname':'rory','uni':'uum','year':2})
datab.append( {'lastname':'toner','firstname':'kevin','uni':'qub','year':4})
datab.append( {'lastname':'hughes','firstname':'johnny','uni':'uuj','year':1})
uni = input('Enter the uni here: ')
find_all(datab,uni)
If you want to search through all the keys then you could change the
if student['uni'] == uni line to
for key, value in student.items():
if value == uni:
Another version: this will allow you to enter a very simple query.
def find_all(datab,query):
query = query.split('OR')
for search_terms in query:
for student in datab:
for key, value in student.items():
if value == search_terms.strip():
print(student)
datab = list()
datab.append( {'lastname':'walker', 'firstname':'matthew','uni':'uuc','year':'1'})
datab.append( {'lastname':'stewart','firstname':'rory','uni':'uum','year':'2'})
datab.append( {'lastname':'toner','firstname':'kevin','uni':'qub','year':'4'})
datab.append( {'lastname':'hughes','firstname':'johnny','uni':'uuj','year':'1'})
query = input('Enter your query here: ')
find_all(datab,query)
Here is my code running with two simple queries
Enter the uni here: uum OR uuc
{'firstname': 'rory', 'lastname': 'stewart', 'uni': 'uum', 'year': 2}
{'firstname': 'matthew', 'lastname': 'walker', 'uni': 'uuc', 'year': 1}
Enter your query here: 1 OR UUM
{'firstname': 'matthew', 'lastname': 'walker', 'uni': 'uuc', 'year': '1'}
{'firstname': 'johnny', 'lastname': 'hughes', 'uni': 'uuj', 'year': '1'}
You just add the word OR between the items and it will search for any item in the dictionary that contains any of the words. N.B. I had to change the uni year to be a string to get it working.
As I've stated. This would be much better with a proper database like SQLite.
You could simplify your all_from function:
def all_from(datab,university):
# Create flag to see if there are results
result = False
for k in datab.keys():
# Knowing that university will always be in the same column
if university == datab[k][2]:
result = True
print datab[k]
if not result:
print 'Nobody goes to University there!'
datab = dict()
datab[1] = ['walker','matthew','uuc',1]
datab[2] = ['stewart','rory','uum',2]
datab[3] = ['toner','kevin','qub',4]
datab[4] = ['hughes','johnny','uuj',1]
datab[5] = ['douglas','kenny','uuc', 3]
datab[6] = ['hooks', 'peter','qub',1]
datab[7] = ['campbell','vicky','uuj',2]
datab[8] = ['crooks','laura','uum',4]
datab[9] = ['irwin','emma','uuc',3]
datab[10] = ['patterson','steve','uuc',1]
university = (raw_input('Enter the University here: '))
all_from(datab,university)
http://www.codeskulptor.org/#user42_wjXMwt73xI_2.py

How to use '*' in Mongodb?

I have 2 variables, sent from ajax, like name and age, their default value is '*'.
when name and age are set, like name = 'a', age = 20, I can query in mongodb(pymongo):
info = list(db.test.find({'name': name, 'age': age}))
But there is time age or name is unset, I have to write:
if age == '*' and name == '*':
info = list(db.test.find())
elif name == '*':
info = list(db.test.find({'age': age}))
elif age == '*':
info = list(db.test.find({'name': name}))
Is there way that I can write a single query? like:
info = list(db.test.find({'name': name, 'age': age}))
One option would be to treat * as {'$exists': True}:
name = {'$exists': True} if name == '*' else name
age = {'$exists': True} if age == '*' else age
info = list(db.test.find({'name': name, 'age': age}))
Or, better solve it on the python side by keeping name and age in the dictionary:
params = {}
if name != '*':
params['name'] = name
if age != '*':
params['age'] = age
info = list(db.test.find(params))
It is unclear what you want the query to return, what the initial values of age and name are. Please create a reproducible example (give an example of some sample docs, the query you are running, what is being returned and what you would like to see returned).
Are you looking for all documents where name (or age) is unset?
db.col.find({'name':'*'})
Are you looking for all documents where name=name or age=age?
db.col.find({ '$or': [{'name': name } , {'age': age} ] })
Please specify what specifically you want the query to return.
I disagree with alecxe however, you shouldn't 'solve on the python side'. You should do more research on how to write queries in MongoDB and let the database cluster do all of the heavy lifting in terms of processing. Just my .02.

Categories

Resources