1
color_table = {"Red":[1,2,3], "Blue":[4,5,6]}

def my_function(colortable):
    print("List is :-",color_table['Red'])

my_function(color_table)

Here, I would like to pass just first element of the color_table dictionary in the function my_function rather than the whole dictionary.
Is it possible to do so?

Leonardo
  • 2,439
  • 33
  • 17
  • 31
  • Note that _first element_ does not make sense with `dict` (mappings). The order of elements in the dict was not even guaranteed before 3.7. You can pass the key, but without passing the dict your function will rely on global variable, so not good approach. Better have the dict inside the function instead. – buran Nov 14 '21 at 08:13
  • What's the issue with passing the whole dictionary? If the function "knows" which key is useful, then pass the whole dictionary and let the function extract the value. If the caller knows which key is useful, then pass the value. – jferard Nov 14 '21 at 10:33

1 Answers1

0

Yes,

you use first key in the dictionnary,

To take the key, convert key to list and take first argument

In one line

my_fonction(color_table[list(color_table.keys())[0]])

Or in multi line

first_key = list(color_table.keys())
first_key = first_key[0]
my_fonction(color_table[first_key])
gaetan1903
  • 34
  • 3
  • What if i dont know the index of value which i intend to extract from dictionary and pass to function? This logic just holds for a dictionary which is fixed in nature but not for variable length or say dynamic in nature? – Ishan Anand Nov 14 '21 at 09:34
  • 1
    Creating a list is not necessary: `next(iter(color_table.keys()))` will do the trick. (Whether the "first element" of the dictionnary has a meaning or not depends on the context.) – jferard Nov 14 '21 at 10:38