Returning a Dictionary:
- A function can return any kind of value you need it to, including more complicated data structures (e.g., dictionaries and lists).
- Example: The following function takes in parts of a name and returns a dictionary representing adding a user to a website.
python
1def addUser(emailAddress, firstName, lastName):
2 #Make a dictionary representing a user
3 userDictionary = {"email": emailAddress, "first":firstName, "last":lastName}
4 return userDictionary
5
6wcuUser01 = addUser("hbulldog@student.wcu.edu", "Harpua", "Bulldog" )
7print(wcuUser01)- The function addUser takes in an email address, and the user’s first and last name, and packs these values into a dictionary in line 3. The value of emailAddress, is stored with the key “email”, and the value of firstName is stored with the key “first” and lastly the value of “lastName” is stored with the key “last”.
- The entire dictionary representing the person is returned at line 6.
- The return value is printed at line 7 with the original three prices of textual information now stored in a dictionary:
Output:
1{'email': 'hbulldog@student.wcu.edu', 'first': 'Harpua', 'last': 'Bulldog'}