I cannot seem to match the user input(num) to id_num to print out the individual license info. I want that when the user is prompted to enter the license number, the code should loop through the dictionary and find its match and print the info that matches the input.
I tried:
if num in driver_license[id_num]:
if num==id_num:
if num==int(id_num):
42456 :{'name': 'jill', 'ethnicity': 'hispanic','eye': 'yellow' ,'height': '6.1'},
44768 :{'name': 'cheroky', 'ethnicity': 'native','eye': 'green' ,'height': '6.7'},
32565 :{'name': 'valentina', 'ethnicity': 'european','eye': 'fair','height': '4.9'}}
print('\n')
print('- ' *45)
for id_num, id_info in driver_license.items():
num = int(input('Enter your driving license number: '))
print(f"Id number: {id_num}")
name=f"{id_info['name']}"
origin= f"{id_info ['ethnicity']}"
eye= f"{id_info['eye']}"
height=f"{id_info['height']}"
if num in driver_license[id_num]:
print(f'\nId number is:{num}')
print(f'Name: {name}')
print(f'Ethnicity: {origin}')
print(f'Eyes color: {eye}')
print(f'Height: {height}\n')
else:
print('Invalid ID')
There is no error but a mismatch of output than expected.
You don't need to loop through the dictionary.
You can instead use get(key, default) to get the entry from the driver_license dictionary using the input license number as the key. You can then set default to some value to handle the case where the key is not in the dict (here I used None).
driver_license = {
"42456" : {'name': 'jill', 'ethnicity': 'hispanic','eye': 'yellow' ,'height': '6.1'},
"44768" : {'name': 'cheroky', 'ethnicity': 'native','eye': 'green' ,'height': '6.7'},
"32565" : {'name': 'valentina', 'ethnicity': 'european','eye': 'fair','height': '4.9'}
}
id_num = input('Enter your driving license number: ')
# if user enters "32565"
id_info = driver_license.get(id_num, None)
# id_info would be:
# {'name': 'valentina', 'ethnicity': 'european','eye': 'fair','height': '4.9'}
if id_info:
print(f'\nId number is:{id_num }')
print(f'Name: {id_info["name"]}')
print(f'Ethnicity: {id_info["ethnicity"]}')
print(f'Eyes color: {id_info["eye"]}')
print(f'Height: {id_info["height"]}\n')
else:
print('Invalid ID')
Related
I need to be able to print all instances of a name within the list of dictionaries. I can't seem to be able to print them in the desired format. It also doesn't work when it's in lowercase and the name is in uppercase.
def findContactsByName(name):
return [element for element in contacts if element['name'] == name]
def displayContactsByName(name):
print(findContactsByName(name))
if inp == 3:
print("Item 3 was selected: Find contact")
name = input("Enter name of contact to find: ")
displayContactsByName(name)
When the name 'Joe' was put in the output is:
[{'name': 'Joe', 'surname': ' Miceli', 'DOB': ' 25/06/2002', 'mobileNo': ' 79444425', 'locality': ' Zabbar'}, {'name': 'Joe', 'surname': 'Bruh', 'DOB': '12/12/2131', 'mobileNo': '77777777', 'locality': 'gozo'}]
When the name 'joe':
[]
Expected output:
name : Joe
surname : Miceli
DOB : 25/06/2002
mobileNo : 79444425
locality : Zabbar
name : Joe
surname : Bruh
DOB : 12/12/2131
mobileNo : 77777777
locality : gozo
Change the first function to:
def findContactsByName(name):
return [element for element in contacts if element['name'].lower() == name.lower()]
To account for the differences in uppercase and lowercase, I've just converted the name in the dictionary and the entered name to lowercase during the comparison part alone.
To be able to print it in the format that you've specified you could make a function for the same as follows:
def printResult(result):
for d in result:
print(f"name: {d['name']}")
print(f"surname: {d['surname']}")
print(f"DOB: {d['DOB']}")
print(f"mobileNo: {d['mobileNo']}")
print(f"locality: {d['locality']}")
print()
result=findContactsByName("joe")
printResult(result)
I modified your program. Now you don't have to worry about the case and the output formatting.
contacts = [{'name': 'Joe',
'surname': ' Miceli', 'DOB': ' 25/06/2002', 'mobileNo': ' 79444425', 'locality': ' Zabbar'},
{'name': 'Joe', 'surname': 'Bruh', 'DOB': '12/12/2131', 'mobileNo': '77777777', 'locality': 'gozo'}]
def findContactsByName(name):
return [element for element in contacts if element['name'].lower() == name.lower()]
def displayContactsByName(name):
for i in range(len(findContactsByName(name))):
for j in contacts[i]:
print('{}: {}'.format(j, contacts[i][j]))
print('\n')
displayContactsByName('Joe')
Case issue can be solved by setting each side of the comparison to UPPERCASE or LOWERCASE.
return [element for element in contacts if element['name'].upper() == name.upper()]
For the format of the print statement you could use the json module:
import json
print(json.dumps( findContactsByName(name), sort_keys=True, indent=4))
I am trying to write a function that, given a dictionary of restaurants, allows you to randomly pick a restaurant based on your choice of one of the values. For example, if you say you want a bakery then it will only give you bakeries.
I have only worked on the code for choosing the type of restaurant so far, and I am struggling with how to generate a random list. So I am checking for a value and, if it has it, would want to add the key to a list. Does anyone have any suggestions on how to do this?
import random
Restaurants ={
"Eureka": ["American", "$$", "Lunch", "Dinner"],
"Le_Pain": ["Bakery", "$$", "Breakfast", "Lunch", "Dinner"],
"Creme_Bakery": ["Bakery", "$", "Snack"]
}
list=[]
def simple_chooser():
print('Would you like to lock a category or randomize? (randomize, type, price, or meal)')
start= input()
if start=="randomize":
return #completely random
elif start=="type":
print("American, Bakery, Pie, Ice_Cream, Bagels, Asian, Chocolate, Italian, Pizza, Thai, Mexican, Japanese, Acai, Mediterranean, or Boba/Coffee?")
type=input()
for lst in Restaurants.values():
for x in lst:
if x==type:
list.append(x)
return(random.choice(list))
To return completely random restaurant suggestions you need to create a list of all the types first and then you can choose one and return the names of the restaurants.
import random
Restaurants ={
"Eureka": ["American", "$$", "Lunch", "Dinner"],
"Le_Pain": ["Bakery", "$$", "Breakfast", "Lunch", "Dinner"],
"Creme_Bakery": ["Bakery", "$", "Snack"]
}
types = ['American', 'Bakery', 'Pie', 'Ice_Cream', 'Bagels', 'Asian', 'Chocolate', 'Italian',
'Pizza', 'Thai', 'Mexican', 'Japanese', 'Acai', 'Mediterranean','Boba/Coffee']
def simple_chooser():
l=[]
print('Would you like to lock a category or randomize? (randomize, type, price, or meal)')
start= input()
if start=="randomize":
type_random = random.choice(types)
for k,v in Restaurants.items():
if v[0] == type_random:
l.append(k)
elif start=="type":
print("American, Bakery, Pie, Ice_Cream, Bagels, Asian, Chocolate, Italian, Pizza, Thai, Mexican, Japanese, Acai, Mediterranean, or Boba/Coffee?")
type_chosen=input()
for k,v in Restaurants.items():
if v[0] == type_chosen:
l.append(k)
return(random.choice(l))
Also, you don't need to return in if-else statements. Once you have your list of Restaurants you can randomly choose a restaurant and return it.
In your loop, you don't have the restaurant name, as you iterate on the values, you would have need something like
for name, props in Restaurants.items():
if props[0] == type:
list.append(name)
return (random.choice(list)) # wait for the whole list to be constructed
With a better naming (don't use type and list that are builtin methods)
def simple_chooser():
start = input('Would you like to lock a category or randomize? (randomize, type, price, or meal)')
if start == "randomize":
return # completely random
elif start == "type":
restaurant_type = input("American, Bakery, Pie, Ice_Cream, Bagels, Asian, Chocolate, Italian, "
"Pizza, Thai, Mexican, Japanese, Acai, Mediterranean, or Boba/Coffee?")
matching_names = [name for name, props in Restaurants.items() if props[0] == restaurant_type]
return random.choice(matching_names)
You make processing difficult because of the design of your data structures.
Here's an idea which should be easily adapted to future needs.
import random
from operator import contains, eq
Restaurants = [
{'name': 'Eureka', 'type': 'American', 'price': '$$', 'meal': ('Dinner',)},
{'name': 'Le_Pain', 'type': 'Bakery', 'price': '$$', 'meal': ('Lunch', 'Dinner')},
{'name': 'Creme_Bakery', 'type': 'Bakery', 'price': '$', 'meal': ('Snack',)}
]
def get_attr(k):
s = set()
for r in Restaurants:
if isinstance(r[k], tuple):
for t in r[k]:
s.add(t)
else:
s.add(r[k])
return s
def choose_restaurant():
categories = ', '.join(Restaurants[0])
while True:
choice = input(f'Select by category ({categories}) or choose random: ')
if choice == 'random':
return random.choice(Restaurants)
if choice in Restaurants[0]:
choices = get_attr(choice)
if (v := input(f'Select value for {choice} from ({", ".join(choices)}): ')) in choices:
op = contains if isinstance(Restaurants[0][choice], tuple) else eq
return [r for r in Restaurants if op(r[choice], v)]
print('Invalid selection\x07')
print(choose_restaurant())
Restaurants is now a list of dictionaries which is easy to extend. You just need to make sure that each new restaurant has the same structure (keys). Also note that the 'meal' value is a tuple even if there's a single value
I want to get data from input that is in yaml format.The data includes user information and music albums information that each user has purchased.Input information is as follows:
2 # this line specify the number of users
- name: user1
age: 18
city: city1
albums:
- album1
- album2
- album3
- name: user2
age: 20
city: city2
albums:
- album2
- album1
- alubm3
3 # this line specify the number of albums
- name: album1
singer: singer1
genre: classic
tracks: 10
- name: album2
singer: singer2
genre: pop
tracks: 22
- name: album3
singer: singer3
genre: pop
tracks: 14
I wrote the following code for this
num_user = int(input())
users_data = {}
albums_data = {}
for i in range(num_user):
name, age, city = input().split()[-1], input().split()[-1], input().split()[-1]
input()
albums=[]
next_line = input()
while next_line.split()[0]=='-' and len(next_line)-len(next_line.lstrip(' '))==4:
albums.append(next_line.split()[-1])
next_line = input()
if len(next_line.split()) < 2:
num_albums = int(next_line)
users_data[name]=[age, city, albums]
for i in range(num_albums):
name, singer, genre, tracks = input().split()[-1],input().split()[-1],\
input().split()[-1], input().split()[-1]
albums_data[name]=[singer, genre, tracks]
Everything is in order until the number of users exceeds one person and I have trouble storing the second user information in the dictionary and all the moving information is stored.
I want this:
{'user1': ['18', 'city1', ['album1', 'album2', 'album3']], 'user2': ['20', 'city2', ['album2', 'album1', 'alubm3']]} {'album1': ['singer1', 'classic', '10'], 'album2': ['beeptunes', 'pop', '22'], 'tekunbede': ['beeptunes', 'pop', '14']}
but get this:
{'user1': ['18', 'city1', ['album1', 'album2', 'album3']], '20': ['city2', 'albums:', ['album1', 'alubm3']]} {'album1': ['singer1', 'classic', '10'], 'album2': ['beeptunes', 'pop', '22'], 'tekunbede': ['beeptunes', 'pop', '14']}
The issue seems to be that once you have processed the last album for the first user you are then calling input() again which is getting the name. Decoupling the input from the processing will help to fix the issue so have a look at creating a function to process a name once its been detected.
so try:
read the input
work out what do based on the input
process the read data
num_user = int(input())
users_data = {}
albums_data = {}
for i in range(num_user):
name, age, city = input().split()[-1], input().split()[-1], input().split()[-1]
input()
albums=[]
next_line = input()
while next_line.split()[0]=='-' and len(next_line)-len(next_line.lstrip(' '))==4:
albums.append(next_line.split()[-1])
next_line = input() # This is the line with the issue
if len(next_line.split()) < 2:
num_albums = int(next_line)
users_data[name]=[age, city, albums]
for i in range(num_albums):
name, singer, genre, tracks = input().split()[-1],input().split()[-1],\
input().split()[-1], input().split()[-1]
albums_data[name]=[singer, genre, tracks]
Here is am example of the list:
{'Item': 'milk', 'Price': '2.0', 'Quantity': '2'}, {'Item': 'egg', 'Price': '12.0', 'Quantity': '1'}]
Here is my code:
def edit_items(info):
xy = info
print('Index | Orders')
for x in enumerate(xy):
print('\n')
print(x)
choice = int(input('Which entry would you like to edit? Choose by index. :'))
print(x[choice])
Id like the user to able to chose an entry by index, and allow them to edit information inside the dictionary.
So far my code prints out:
Index | Orders
(0, {'Item': 'milk', 'Price': '2.0', 'Quantity': '2'})
(1, {'Item': 'egg', 'Price': '12.0', 'Quantity': '1'})
But i have no idea how to choose one, assign It to a variable and carry out the ability to edit whats inside.
Cheers. Nalpak_
def edit_items(info):
xy = info
# to make multiple edits.
while True:
print('Index | Orders')
for x in range(len(xy)):
print(x,xy[x])
choice = int(input('Which entry would you like to edit?\nChoose by index: '))
print(xy[choice])
edit = input('What you want to edit: ') # Key val of dict
value = input("Enter: ") # Value for the specific key in dict
xy[choice][edit] = value
print('list updated.')
print(xy[choice])
more_edits = input('\nDo you want to make more edits?(y/n): ')
if more_edits == 'n':
break
edit_items(info)
this will help you make multiple edits.
If you want to edit an item in a dictionary, you can easily do it by accessing it by the key.
First, we set up the data
xy = [{'Item': 'milk', 'Price': '2.0', 'Quantity': '2'}, {'Item': 'egg', 'Price': '12.0', 'Quantity': '1'}]
Then if I understood you correctly, this edit_items method should do exactly what you need:
def edit_items(i):
name = input('Type in a new item name: ')
xy[i]['Item'] = name # 'Item' is the key.
Everything else is pretty much the same:
print('Index | Orders')
for x in enumerate(xy):
print('\n')
print(x)
choice = int(input('Which entry would you like to edit? Choose by index. :'))
print(xy[choice])
edit_items(choice)
print(xy)
If you want, you can also use input for getting a key (property) of an item you want to edit.
I'm kind of new to python, and I need some help. I'm making an employee list menu. My list of dictionaries is:
person_infos = [ {'name': 'John Doe', 'age': '46', 'job position': 'Chair Builder', 'pay per hour': '14.96','date hired': '2/26/19'},
{'name': 'Phillip Waltertower', 'age': '19', 'job position': 'Sign Holder', 'pay per hour': '10','date hired': '5/9/19'},
{'name': 'Karen Johnson', 'age': '40', 'job position': 'Manager', 'pay per hour': '100','date hired': '9/10/01'},
{'name': 'Linda Bledsoe', 'age': '60', 'job position': 'CEO', 'pay per hour': '700', 'date hired': '8/24/99'},
{'name': 'Beto Aretz', 'age': '22', 'job position': 'Social Media Manager', 'pay per hour': '49','date hired': '2/18/12'}]
and my "search the list of dicts input function" is how the program is supposed to print the correct dictionary based on the name the user inputs:
def search_query(person_infos):
if answer == '3':
search_query = input('Who would you like to find: ')
they_are_found = False
location = None
for i, each_employee in enumerate(person_infos):
if each_employee['name'] == search_query:
they_are_found = True
location = i
if they_are_found:
print('Found: ', person_infos[location]['name'], person_infos[location]['job position'], person_infos[location]['date hired'], person_infos[location]['pay per hour'])
else:
print('Sorry, your search query is non-existent.')
and I also have this-
elif answer =='3':
person_infos = search_query(person_infos)
This seems like a step in the right direction, but for
search_query = input('Who would you like to find: ')
if I input of the names in person_infos, like "John Doe," it just prints the last dictionary's information (no matter which specific dictionary it is, the last one in the order will always be outputted) instead of John Doe's. in this case, it would only print "Beto Aretz's."
Can someone please help? It's something I've been struggling on for a while and it would be awesome.
I've researched so much and I could not find something with things that I either knew how to do, or were the input search.
Thanks,
LR
At first glance it looks like because your location=i is not indented inside your if statement so it is getting set to the latest i on each iteration of the for loop. Let me know if this helps.
def search_query(person_infos):
if answer == '3':
search_query = input('Who would you like to find: ')
they_are_found = False
location = None
for i, each_employee in enumerate(person_infos):
if each_employee['name'] == search_query:
they_are_found = True
location = i
if they_are_found:
print('Found: ', person_infos[location]['name'], person_infos[location]['job position'], person_infos[location]['date hired'], person_infos[location]['pay per hour'])
else:
print('Sorry, your search query is non-existent.')