-1

i am new to python and i am having trouble on python dictionaries this is my code:

dic = {"days":["mon","tue","wed"]}
print(dic[0])

the output am expecting is

"mon","tue","wed"

But i keep getting this error :

    print(dic[0])
KeyError: 0

please help me... Thank You!

  • 1
    `dic['days']` instead of `dic[0]`, if you want to obtain according to the insertion order, consider using `list(dic.values())[0]`. – Mechanic Pig Jun 18 '22 at 16:20
  • Or this way - `print(dic['days'][0])` It's because your `values` in the dict is a `list`. – Daniel Hao Jun 18 '22 at 16:21
  • 2
    Checkout https://stackoverflow.com/questions/15114843/accessing-dictionary-value-by-index-in-python This duplicates that thread. – AvitanD Jun 18 '22 at 16:22
  • 1
    Does this answer your question? [Accessing dictionary value by index in python](https://stackoverflow.com/questions/15114843/accessing-dictionary-value-by-index-in-python) – AvitanD Jun 18 '22 at 16:24
  • i want by indexing please.... no ["days"] answers... if possible – Prison Mike Jun 18 '22 at 16:38

3 Answers3

1

Try:

print(dic['days']) 

You refer to values by keys. It returns a list of elements. Then, if you want a specific element, just use:

print(dic['days'][0])

...as you would do with a normal list.

jarsonX
  • 117
  • 1
  • 8
1

Dictionaries in python are accessed via key not index as position was not guaranteed until 3.7.

dic = {"days":["mon","tue","wed"]}
print(dic["days"])
ljmc
  • 4,830
  • 2
  • 7
  • 26
0

Thanks everyone i Found the answer

dic = {"days":["mon","tue","wed"], "months":["jan","feb","mar"]}
print(list(dic.values())[0])

the output will be:

['mon', 'tue', 'wed']

Thank you

  • 1
    Note, this is will only work with python 3.7 and above ([ref](https://mail.python.org/pipermail/python-dev/2017-December/151283.html)). – ljmc Jun 18 '22 at 16:50