Python Forum
Return both key and value by calling only dict value
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Return both key and value by calling only dict value
#1
Hi I want to write a 3-5 line function, very small that returns state name and code as a tupple. e.g. if input "CA" return "California", "CA"

def get_state_with_code(state_code):
    
    
    return ()
us_state_code = {
    'Alabama': 'AL',
    'Alaska': 'AK',
    'American Samoa': 'AS',
    'Arizona': 'AZ',
    'Arkansas': 'AR',
    'California': 'CA',
    'Colorado': 'CO',
    'Connecticut': 'CT',
    'Delaware': 'DE',
    'District of Columbia': 'DC',
    'Florida': 'FL',
    'Georgia': 'GA',
    'Guam': 'GU',
    'Hawaii': 'HI',
    'Idaho': 'ID',
    'Illinois': 'IL',
    'Indiana': 'IN',
    'Iowa': 'IA',
    'Kansas': 'KS',
    'Kentucky': 'KY',
    'Louisiana': 'LA',
    'Maine': 'ME',}
Reply
#2
why not swap keys and values in the dict if you are going to search by state code?
otherwise, as it is now, you need to iterate over items and if value is what you look for - return the key.
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
(Feb-06-2021, 07:55 AM)buran Wrote: why not swap keys and values in the dict if you are going to search by state code?
otherwise, as it is now, you need to iterate over items and if value is what you look for - return the key.


Can you help me with the code? I am pretty new to python
Reply
#4
To swap the values and codes is simple:
us_code_state = {value:key for key, value in us_state_code.items()}
as for the function, if "us_code_state" is a global variable:
def get_state_with_code(state_code):
    return us_code_state[state_code], state_code
or if you send both dict and state_code to the function:
def get_state_with_code(state_code, dic):
    return dic[state_code], state_code

# Call with:
get_state_with_code('AL', us_code_state)
but simplest is to not use a function, but to use the dictionary directly:
print(us_code_state['AL'], 'AL')
or as a tuple:
print((us_code_state['AL'], 'AL'))
or, if it is important to use your original dictionary:
def get_state_with_code(state_code):
    for key, value in us_state_code.items():
        if value == state_code:
            return key, value
    return None
where the last line is to ensure a value if nothing is found (actually the default if nothing is returned)
Jeff900 likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Sort a dict in dict cherry_cherry 4 75,518 Apr-08-2020, 12:25 PM
Last Post: perfringo
  return dict in tuple bb8 6 3,554 Feb-26-2018, 08:16 PM
Last Post: bb8

Forum Jump:

User Panel Messages

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