Python Forum
[split] capitalize dict keys for display in string
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[split] capitalize dict keys for display in string
#1
(Oct-10-2019, 07:09 AM)perfringo Wrote: In order to save repeated typing one can use dictionaries and try...except:

email = 'somebody@somewhere'                                                           
subject = 'I lost my license'                                                          
header = (f'Dear customer {email},\n\n' 
           'Thank you for contacting our company.') 
footer = 'Thank you\n\nCompany customer service'
categories = {'i lost my license': 'You will be contacted via email to verify you license request.\n\n',
              'problem saving file': 'Saving file is done by pressing CTRL-S (Windows} or CMD- (Mac).\n\n'}

try: 
    print(f'{header}{categories[subject.lower()]}{footer}') 
except KeyError: 
    print('Sorry, dada-dada-blah-blah') 
This way one needs to add only key-value pair to categories dictionary for additional subject.

Hi!

I'm not sure if it is appropriate for me to ask a question here, as it is not my thread. If it is not appropriate, my apologies, and I'd be grateful, relieved and agreeable if it is moved to a new thread.

Well, my question is that you, as usual, made wise suggestions to my always improvable code. (I'm very grateful to you for that, as it makes me widen my knowledge.) I made the necessary adjustments to my code and got this:

# license_02.py
#
 
email1 = input('Please, enter your email:\n')
subject1 = input('Please, enter your Message Subject:\n')
subject1 = subject1.lower()
messageBody1 = input('Please, enter your Message Body:\n')
                                                         
header = (f'Dear customer {email1},\n\n' 
           'Thank you for contacting our company.') 
footer = 'Thank you\n\nCompany customer service'
categories = {'i lost my license': 'You will be contacted via email to verify your license request.\n\n',
              'problem saving file': 'Saving file is done by pressing CTRL-S (Windows} or CMD- (Mac).\n\n'}

def getList(categories):
    for cat in categories.keys():
        return cat.capitalize()
 
try: 
    print(f'{header}{categories[subject1.lower()]}{footer}') 
except KeyError: 
    print(f"Sorry, you should write, word for word, one of these: '{getList(categories)}' on the message subject.")
    
and it works great on the two categories shown, but when I tried to improve also my code at the except KeyError:, by wanting to display all the keys of the dictionary, like this ideal output:
Output:
Sorry, you should write, word for word, one of these: 'I lost my license', 'Problem saving file', [ HERE FUTURE KEYS], on the message subject.
I managed to capitalize back the keys of the dictionary, but the only key printed is the first one:
Output:
Please, enter your email: User25@yeehaamail Please, enter your Message Subject: This is a test. Please, enter your Message Body: Blah blah blah ... Sorry, you should write, word for word, one of these: 'I lost my license' on the message subject. >>>
As usual, I tried different approaches, getting all kinds of error:
Error:
NameError: name 'capitalize' is not defined
Error:
AttributeError: 'list' object has no attribute 'keys'
Error:
TypeError: unhashable type: 'dict'
Error:
TypeError: unhashable type: 'dict_keys'
Error:
TypeError: unhashable type: 'slice'
Error:
TypeError: keys() takes no arguments (1 given)
Once again, I apologise if I'm posting in the wrong place. Please be free to move it where you see it feasible.

Thanks and all the best,
Reply
#2
as it is now your getList will return just the first key (see the indentation of the return statement)
def getList(categories):
    for cat in categories.keys():
        return cat.capitalize()
probably you want
def getList(categories):
    return [cat.capitalize() for  cat in categories.keys()] # this will return list of keys()
    # return ', '.join(cat.capitalize() for  cat in categories.keys()) # this will return comma separated string
if you get list from function you will need to construct the comma separated string in the f-string

print(f"Sorry, you should write, word for word, one of these: \"{', '.join(getList(categories))}\" on the message subject.")
     
or you can directly change the print function
print(f"Sorry, you should write, word for word, one of these: \"{', '.join(map(str.capitalize, categories.keys()))}\" on the message subject.")
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Hello,

Your getList function returns immediately after the first iteration because the return statement is inside the for loop.
If you want it to return a result with all the string capitalized in it, build a list and return it after the loop, for example :

mylist = []
for cat in categories.keys():
  mylist.append(cat.capitalize())
return mylist
Reply
#4
Something like below?

>>> f"You must pick one from: {', '.join(key.capitalize() for key in categories)}"             
'You must pick one from: I lost my license, Problem saving file'
Or with quotation marks:

>>> f"""You must pick one from: {', '.join(f'"{key.capitalize()}"' for key in categories)}"""                                                                                     
'You must pick one from: "I lost my license", "Problem saving file"'
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Information Unable to display joystick's value from Python onto display box MelfoyGray 2 159 Nov-11-2020, 02:23 AM
Last Post: MelfoyGray
  How to capitalize in dictionary Inkanus 2 160 Oct-28-2020, 01:20 PM
Last Post: Inkanus
  Split dict of lists into smaller dicts of lists. pcs3rd 3 329 Sep-19-2020, 09:12 AM
Last Post: ibreeden
  Split string between two different delimiters, with exceptions DreamingInsanity 2 283 Aug-24-2020, 08:23 AM
Last Post: DreamingInsanity
  String index out of bounds ( Python : Dict ) kommu 2 431 Jun-25-2020, 08:52 PM
Last Post: menator01
  split string enigma619 1 277 May-20-2020, 02:47 PM
Last Post: perfringo
  TypeError: __repr__ returned non-string (type dict) shockwave 0 556 May-17-2020, 05:56 PM
Last Post: shockwave
  Split string with multiple delimiters and keep the string in "groups" DreamingInsanity 4 537 May-12-2020, 09:31 AM
Last Post: DeaD_EyE
  Sort a dict in dict cherry_cherry 4 589 Apr-08-2020, 12:25 PM
Last Post: perfringo
  dict elements are sometimes treated as List and sometimes as String phython_mdr 4 548 Apr-01-2020, 12:47 PM
Last Post: phython_mdr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020