How to strip and use title() in list and dictionary - python

I know this is a newbie question. But I'm still having trouble using .strip() and .title() with a list or a dictionary. I'd like to normalize both but can't find how.
favorite_languages = {
'JENNA': 'python',
'louis': 'C',
'liOnEl': 'Ruby',
'maude': 'Javascript',
}
friends = [' JeNNa', 'LIONEL ']
for name in favorite_languages.keys():
print(name.title().strip())
if name.title().strip() in friends:
print("Hi " + name + ", I can see your favorite language is " +
favorite_languages[name] + "!")

First, normalise your favorite_languages:
In [605]: fav_lang_norm = { x.strip().title() : favorite_languages[x] for x in favorite_languages }; fav_lang_norm
Out[605]: {'Jenna': 'python', 'Lionel': 'Ruby', 'Louis': 'C', 'Maude': 'Javascript'}
Then, normalise your friends list:
In [606]: friends_norm = [x.strip().title() for x in friends]; friends_norm
Out[606]: ['Jenna', 'Lionel']
Iterate over the normalised dictionary:
for name, language in fav_lang_norm.items():
if name in friends_norm:
print("Hi " + name + ", I can see your favorite language is " +
language + "!")
You'd better hope your friends list is case insensitive...
Second approach, consider you have a huge favorite_languages dictionary with a million records:
favorite_languages = {...} # 1 million
Step 1: Normalise your favourite_languages dict only:
fav_lang_norm = { x.strip().title() : favorite_languages[x] for x in favorite_languages }
Step 2: Iterate over your friends list:
for name in friends: # friends is not normalised
name_norm = name.strip().title()
if name_norm in fav_lang_norm:
print("Hi " + name_norm + ", I can see your favorite language is " +
fav_lang_norm[name_norm] + "!")

Related

What is the reason for the error AttributeError: 'str' object has no attribute 'get' and how can it be fixed?

I am having an issue getting the following code to print:
pizza_order = {'name': 'Matthew', 'size': 'large', 'crust': 'stuffed', 'toppings': 'sausage, bacon, beef, ham'}
orders = []
for value in pizza_order.values():
pizza = "Thank you for your order, " + value.get('name') + "\nYou have ordered a " + value.get('size') + ", " + value.get('crust') + " crust pizza with the following toppings:\n" + value.get('toppings')
orders.append(pizza)
print(orders)
The error I am getting reads:
Traceback (most recent call last):
line 33, in <module>
pizza = "Thank you for your order, " + value.get('name') + "\nYou have ordered a " + value.get('size') + ", " + value.get('crust') + " crust pizza with the following toppings:\n" + value.get('toppings')
AttributeError: 'str' object has no attribute 'get'
values() iterates of the dictionary's values - Matthew, large, etc. Since the dictionary includes a single order, you don't need a loop there - just run the print directly.
You are doing wrong you need pizza_order as list otherwise there is no reason to create order=[]
pizza_order = [{'name': 'Matthew', 'size': 'large', 'crust': 'stuffed', 'toppings': 'sausage, bacon, beef, ham'}]
orders = []
for value in pizza_order:
pizza = "Thank you for your order, " + value.get('name') + "\nYou have ordered a " + value.get('size') + ", " + value.get('crust') + " crust pizza with the following toppings:\n" + value.get('toppings')
orders.append(pizza)
print(orders)
output:
['Thank you for your order, Matthew\nYou have ordered a large, stuffed crust pizza with the following toppings:\nsausage, bacon, beef, ham']
Your for-loop is iterating through the pizza_order dictionary instead of the orders array.
pizza_order.values() returns the values of the dict ["Matthew", "large", ...]
If you just want to display the order and add to the orders array you don't need to use a loop.
pizza_order = {'name': 'Matthew', 'size': 'large', 'crust': 'stuffed', 'toppings': 'sausage, bacon, beef, ham'}
orders = []
pizza = "Thank you for your order, " + pizza_order.get('name') + "\nYou have ordered a " + pizza_order.get('size') + ", " + pizza_order.get('crust') + " crust pizza with the following toppings:\n" + pizza_order.get('toppings')
orders.append(pizza)
print(orders)
It is because value is not defined.
It needs to be in the format dictionaryname.get("key") change value to pizza_order and it should work.
Append needs to be out of the loop
pizza_order = {'name': 'Matthew', 'size': 'large', 'crust': 'stuffed',
'toppings': 'sausage, bacon, beef, ham'}
orders = []
for value in pizza_order:
pizza = "Thank you for your order, " + pizza_order.get('name') + "\nYou
have ordered a " + pizza_order.get('size') + ", " +
pizza_order.get('crust') + " crust pizza with the following toppings:\n"
+ pizza_order.get('toppings')
orders.append(pizza)
print(orders) OR print(pizza) #You choose

Search in List; Display names based on search input

I have sought different articles here about searching data from a list, but nothing seems to be working right or is appropriate in what I am supposed to implement.
I have this pre-created module with over 500 list (they are strings, yes, but is considered as list when called into function; see code below) of names, city, email, etc. The following are just a chunk of it.
empRecords="""Jovita,Oles,8 S Haven St,Daytona Beach,Volusia,FL,6/14/1965,32114,386-248-4118,386-208-6976,joles#gmail.com,http://www.paganophilipgesq.com,;
Alesia,Hixenbaugh,9 Front St,Washington,District of Columbia,DC,3/3/2000,20001,202-646-7516,202-276-6826,alesia_hixenbaugh#hixenbaugh.org,http://www.kwikprint.com,;
Lai,Harabedian,1933 Packer Ave #2,Novato,Marin,CA,1/5/2000,94945,415-423-3294,415-926-6089,lai#gmail.com,http://www.buergimaddenscale.com,;
Brittni,Gillaspie,67 Rv Cent,Boise,Ada,ID,11/28/1974,83709,208-709-1235,208-206-9848,bgillaspie#gillaspie.com,http://www.innerlabel.com,;
Raylene,Kampa,2 Sw Nyberg Rd,Elkhart,Elkhart,IN,12/19/2001,46514,574-499-1454,574-330-1884,rkampa#kampa.org,http://www.hermarinc.com,;
Flo,Bookamer,89992 E 15th St,Alliance,Box Butte,NE,12/19/1957,69301,308-726-2182,308-250-6987,flo.bookamer#cox.net,http://www.simontonhoweschneiderpc.com,;
Jani,Biddy,61556 W 20th Ave,Seattle,King,WA,8/7/1966,98104,206-711-6498,206-395-6284,jbiddy#yahoo.com,http://www.warehouseofficepaperprod.com,;
Chauncey,Motley,63 E Aurora Dr,Orlando,Orange,FL,3/1/2000,32804,407-413-4842,407-557-8857,chauncey_motley#aol.com,http://www.affiliatedwithtravelodge.com
"""
a = empRecords.strip().split(";")
And I have the following code for searching:
import empData as x
def seecity():
empCitylist = list()
for ct in x.a:
empCt = ct.strip().split(",")
empCitylist.append(empCt)
t = sorted(empCitylist, key=lambda x: x[3])
for c in t:
city = (c[3])
print(city)
live_city = input("Enter city: ")
for cy in city:
if live_city in cy:
print(c[1])
# print("Name: "+ c[1] + ",", c[0], "| Current City: " + c[3])
Forgive my idiotic approach as I am new to Python. However, what I am trying to do is user will input the city, then the results should display the employee's last name, first name who are living in that city (I dunno if I made sense lol)
By the way, the code I used above doesn't return any answers. It just loops to the input.
Thank you for helping. Lovelots. <3
PS: the format of the empData is: first name, last name, address, city, country, birthday, zip, phone, and email
You can use the csv module to read easily a file with comma separated values
import csv
with open('test.csv', newline='') as csvfile:
records = list(csv.reader(csvfile))
def search(data, elem, index):
out = list()
for row in data:
if row[index] == elem:
out.append(row)
return out
#test
print(search(records, 'Orlando', 3))
Based on your original code, you can do it like this:
# Make list of list records, sorted by city
t = sorted((ct.strip().split(",") for ct in x.a), key=lambda x: x[3])
# List cities
print("Cities in DB:")
for c in t:
city = (c[3])
print("-", city)
# Define search function
def seecity():
live_city = input("Enter city: ")
for c in t:
if live_city == c[3]:
print("Name: "+ c[1] + ",", c[0], "| Current City: " + c[3])
seecity()
Then, after you understand what's going on, do as #Hoxha Alban suggested, and use the csv module.
The beauty of python lies in list comprehension.
empRecords="""Jovita,Oles,8 S Haven St,Daytona Beach,Volusia,FL,6/14/1965,32114,386-248-4118,386-208-6976,joles#gmail.com,http://www.paganophilipgesq.com,;
Alesia,Hixenbaugh,9 Front St,Washington,District of Columbia,DC,3/3/2000,20001,202-646-7516,202-276-6826,alesia_hixenbaugh#hixenbaugh.org,http://www.kwikprint.com,;
Lai,Harabedian,1933 Packer Ave #2,Novato,Marin,CA,1/5/2000,94945,415-423-3294,415-926-6089,lai#gmail.com,http://www.buergimaddenscale.com,;
Brittni,Gillaspie,67 Rv Cent,Boise,Ada,ID,11/28/1974,83709,208-709-1235,208-206-9848,bgillaspie#gillaspie.com,http://www.innerlabel.com,;
Raylene,Kampa,2 Sw Nyberg Rd,Elkhart,Elkhart,IN,12/19/2001,46514,574-499-1454,574-330-1884,rkampa#kampa.org,http://www.hermarinc.com,;
Flo,Bookamer,89992 E 15th St,Alliance,Box Butte,NE,12/19/1957,69301,308-726-2182,308-250-6987,flo.bookamer#cox.net,http://www.simontonhoweschneiderpc.com,;
Jani,Biddy,61556 W 20th Ave,Seattle,King,WA,8/7/1966,98104,206-711-6498,206-395-6284,jbiddy#yahoo.com,http://www.warehouseofficepaperprod.com,;
Chauncey,Motley,63 E Aurora Dr,Orlando,Orange,FL,3/1/2000,32804,407-413-4842,407-557-8857,chauncey_motley#aol.com,http://www.affiliatedwithtravelodge.com
"""
rows = empRecords.strip().split(";")
data = [ r.strip().split(",") for r in rows ]
then you can use any condition to filter the list, like
print ( [ "Name: " + emp[1] + "," + emp[0] + "| Current City: " + emp[3] for emp in data if emp[3] == "Washington" ] )
['Name: Hixenbaugh,Alesia| Current City: Washington']

how to find out how many 'name' are in a list

I create a bot for telegram and ran into the problem of counting the number of values to display the Inline keyboard. I have a list and data that can change and I need to bring in the keyboard all names and addresses in the Inline, only I would like this keyboard to adjust to the number of values (I know how to create Inline-buttons that show all names and addresses. But I am necessary that each button has its own callback)
text=[{'id': 'fd65865b-0f43-468b-80a5-04d5c9f90086', 'vendorId': '232231', 'name': 'магазин-кафетерій', 'location': {'settlement': 'Київ', 'addressLine': 'м.Київ вул.А.Ахматової 35'}, 'freeVisit': False}, {'id': '2a2d898c-853c-453b-a8c3-0acd0e1ebc8a', 'vendorId': '232830', 'name': 'магазин', 'location': {'settlement': 'Київ', 'addressLine': 'м.Київ вул.Радунська,13-А'}, 'freeVisit': False}.....]
selectKeyboard = telebot.types.InlineKeyboardMarkup( row_width=1)
lenname=[i.split("name")[0] for i in text]
print(lenname)
if 0<lenname<2:
for i in range(len(text)):
one=types.InlineKeyboardButton(text=str(text[0]['name']),callback_data="first")
selectKeyboard.add(one)
if 1<lenname<3:
for i in range(len(text)):
one=types.InlineKeyboardButton(text=str(text[0]['name'])+" ",callback_data="first")
two=types.InlineKeyboardButton(text=str(text[1]['name'])+" ",callback_data="second")
selectKeyboard.add(one,two)
if 2<lenname<4:
for i in range(len(text)):
one=types.InlineKeyboardButton(text=str(text[0]['name'])+" ",callback_data="first")
two=types.InlineKeyboardButton(text=str(text[1]['name'])+" ",callback_data="second")
three = types.InlineKeyboardButton(text=str(text[2]['name']) + " " ,callback_data="three")
selectKeyboard.add(one,two,three)
And ....
I expect the output of dynamic keyboard, but the actual output is 1 Inline button
I understood how to do it. I sumed all i
for i in range(len(text)):
name = text[i]['name']
vendor = text[i]['vendorId']
address=text[i]['location']['addressLine']
pprint(name)
sumaI+=i
print(sumaI)
selectKeyboard = telebot.types.InlineKeyboardMarkup( row_width=1)
if sumaI==0:
for i in range(len(text)):
one=types.InlineKeyboardButton(text=str(text[0]['name'])+" "+str(text[0]['location']['addressLine']),callback_data="first")
selectKeyboard.add(one)
elif sumaI==1:
for i in range(len(text)):
one=types.InlineKeyboardButton(text=str(text[0]['name'])+" "+str(text[0]['location']['addressLine']),callback_data="first")
two=types.InlineKeyboardButton(text=str(text[1]['name'])+" "+str(text[1]['location']['addressLine']),callback_data="second")
selectKeyboard.add(one,two)
elif sumaI==3:
for i in range(len(text)):
one=types.InlineKeyboardButton(text=str(text[0]['name'])+" "+str(text[0]['location']['addressLine']),callback_data="first")
two=types.InlineKeyboardButton(text=str(text[1]['name'])+" "+str(text[1]['location']['addressLine']),callback_data="second")
three = types.InlineKeyboardButton(text=str(text[2]['name']) + " " + str(text[2]['location']['addressLine']),
callback_data="three")
selectKeyboard.add(one,two,three)

'print key_1 + value_1+value_2 + good ' by using two dictionaries ?? nothing else

dic = {
'key_1':['val_1','val_2'],
'key_2':['val_3','val_4'],
'key_3':['val_5','val_6']
}
info = {
'i_1':'good',
'i_2':'bad'
}
for k,v in dic.items()
print 'Jack scrd'+info[i_2]+"in both subjects"+dic[val1]+'&'+dic[val2]
I know the print code is not right but gave it here for understanding what I really wanted to do here. I want only the above similar line in printing command.
The following does this. The format command allows you to easily substitute {} with the variables of your choice in a string. When it comes to the dictionary dic[k] would render all the lists which ['val_1','val_2'] is one. So you would give dic[k][0] to get the first value, and dic[k][1] to get the second value.
for k,v in dic.items():
msg = 'Jack scrd {} in both subjects {} & {}'
print msg.format(info['i_2'], dic[k][0], dic[k][1])
# Jack scrd bad in both subjects val_1 & val_2
# Jack scrd bad in both subjects val_5 & val_6
# Jack scrd bad in both subjects val_3 & val_4
Perhaps you want to do this?
Remove the for loop
print 'Jack scrd'+info['i_2']+'in both subjects'+str(dic['key_1'][0])+"&"+str(dic['key_1'][1])
you can use .join to join all list items with a given separator. If you want to print all keys of dic you can use:
dic = {
'key_1':['val_1','val_2'],
'key_2':['val_3','val_4'],
'key_3':['val_5','val_6']
}
info = {
'i_1':'good',
'i_2':'bad'
}
for keys in dic:
# .join will join all list items for a particular key with & and store it in variable subjects
subjects = ' & '.join(dic[keys])
print "jack scored " + info['i_1'] + " in both subjects " + subjects
output:
jack scored good in both subjects val_1 & val_2
jack scored good in both subjects val_5 & val_6
jack scored good in both subjects val_3 & val_4
place_iraq = {
'shrine_1' : ['karbala','imam hussein as.'],
'shrine_2' : ['najaf', 'imam ali as.'],
'yard' : ['karbala', 'wadi-us-salam'],
'shrine_3' : ['karbala', 'abbas as.']
}
type = {
't1':'shrine',
't2': 'grave yard'
}
print 'The '+str(type['t1'])+' of '+str(place_iraq['shrine_1'][1])+' is situated in ' +\
str(place_iraq['shrine_1'][0])
print 'The '+str(type['t1'])+' of '+str(place_iraq['shrine_2'][1])+' is situated in ' +\
str(place_iraq['shrine_2'][0])
print 'The '+str(type['t1'])+' of '+str(place_iraq['shrine_3'][1])+' is situated in ' +\
str(place_iraq['shrine_3'][0])
print 'The '+str(type['t2'])+' of '+str(place_iraq['yard'][1])+' is situated in ' +\
str(place_iraq['yard'][0])

Looping over a list within a dict

I'm new to python, so bear with me.
I have a dict containing lists:
ophav = {'ill': ['Giunta, John'], 'aut': ['Fox, Gardner', 'Doe, John'], 'clr': ['Mumle, Mads'], 'trl': ['Cat, Fat']}
The key names ('ill', 'aut', ...) and the number of items in the lists will be different on each run of the script.
I'd love to do something like:
opfmeta = []
for key, person in ophav.items():
opfmeta.append('<dc:creator role="' + key + '">' + person + '</dc:creator>')
I know this is not working ("cannot concatenate 'str' and 'list' objects") - I have to loop over the list within the dict somehow. How do I do that?
Edit: I need separate entries for each person, like:
<dc:creator role="ill">Fox, Gardner</dc:creator>
<dc:creator role="ill">Doe, John</dc:creator>
You can do that using ' & '.join():
opfmeta = []
for key, person in ophav.items():
opfmeta.append('<dc:creator role="' + key + '">' + ' & '.join(person) + '</dc:creator>')
This will join all the elements of the list together with the specified delimiter (in this case ' & ') so your result will something like this:
<dc:creator role="ill">Fox, Gardner & Doe, John</dc:creator>
You can check out the full working demonstration HERE
Answer to your updated question:
ophav = {'ill': ['Giunta, John'], 'aut': ['Fox, Gardner', 'Doe, John'], 'clr': ['Mumle, Mads'], 'trl': ['Cat, Fat']}
opfmeta = []
for key, person in ophav.items():
for i in person:
opfmeta.append('<dc:creator role="' + key + '">' + i + '</dc:creator>')
for i in opfmeta:
print i
[OUTPUT]
<dc:creator role="ill">Giunta, John</dc:creator>
<dc:creator role="aut">Fox, Gardner</dc:creator>
<dc:creator role="aut">Doe, John</dc:creator>
<dc:creator role="clr">Mumle, Mads</dc:creator>
<dc:creator role="trl">Cat, Fat</dc:creator>
NEW DEMO

Categories