-2

What is the best syntax to reference the characters in a reference to dictionary item? How do I make it indexable?

>>> myd = {'abc':'123','def':'456','ghi':'789'}
>>> myd
{'def': '456', 'ghi': '789', 'abc': '123'}
>>> type(myd)
<class 'dict'>
>>> s=myd['def']
>>> s
'456'
>>> type(s)
<class 'str'>
>>> s[0]
'4'
>>> s[2]
'6'
>>> myd['def'].[0]
SyntaxError: invalid syntax
Wade
  • 11
  • 2
  • 2
    `myd['def']` *produces* a string. As you showed in your first example, you do not need a `.` to index *into* a string – wwii Feb 19 '18 at 16:39
  • `What is the best syntax to ...` - one that works and is easy to understand when read. – wwii Feb 19 '18 at 16:46
  • I think your question is misleading. First you try to create syntactically valid code, then you can think about "best syntax". Also: What IDE do you use? It could detect these simple errors. – Xan-Kun Clark-Davis Feb 19 '18 at 17:20

2 Answers2

1

Just remove the . and it will work.

You have not actually sliced your string. Once you get the value myd['def'] it returns a string. You then need to use [] to slice it. [0] in this case however adding a . is just a syntax error in Python.

This link describes slicing strings

Xantium
  • 11,201
  • 10
  • 62
  • 89
1

myd['def'] returns you the string '456'. You can access a specific index of an array using the same bracket notation that most languages support. Hence, myd['def'][0] will return the string literal '4'

Skam
  • 7,298
  • 4
  • 22
  • 31