video 30 dict within funtion

+1 wandering morg · December 24, 2014
how do i print the dictionary that is defined within the function ? the "**items"

Post a Reply

Replies

Oldest  Newest  Rating
+1 Vaggelis Theodoridis · December 24, 2014
def my_function(**some_keyword_arguments):
 for key, value in some_keyword_arguments.items():
   print(key, value)

# I used a "random" name for argument(some_keyword_arguments),(actually represents keyword arguments) just so people can understand that we can put whatever we want, but we usually use the word "kwargs".

About dictionaries:
If you want to iterate through keys and values: my_dict.items()
If you want to iterate only through keys: my_dict.keys()
If you want to iterate only through values: my_dict.values()

About **kwargs:
The important thing here is the double asterisks (**), which say that the arguments that the function will receive they will be keyword arguments and they will be maybe more than one(it helps when you use a function with 1 or 5 or you don't even know how many keyword arguments it will receive)

Example: my_function(my_name="Vaggelis") or my_function(my_name="Vaggelis", my_surname="Theo")

Sorry for the long post but **kwargs are a bit strange when you first see them so i thought it's a chance for an explanation in case someone see them for the first time
  • 1

Python

107,336 followers
About

This section is all about snakes! Just kidding.

Links
Moderators
Bucky Roberts Administrator