0

my dictionary looks like:

account is: {'Discover': ['username', 'dddddd']}

I've tried:

print(account[0])

but it doesn't work.

Im trying to achieve printing out:

Discover

If someone could help me out? Its been a little while.

Thank you

Jshee
  • 2,620
  • 6
  • 44
  • 60

4 Answers4

3

Since Discover is the only key you could do print account.keys()[0].

But if you ever had more keys this won't work every time since dictionaries are arbitrarily ordered (in other words, have no sense of order), you will need to iterate over the keys() list, or simply print account.keys() to print the whole keys list.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • This is throwing: TypeError: 'dict_keys' object does not support indexing – Jshee Dec 17 '15 at 18:04
  • 1
    @user700070That's because you are using Python 3 (you didn't mention it in your question). In Python 3 you need to convert keys() to a list: `print (list(account.keys())[0])` – DeepSpace Dec 17 '15 at 18:08
1

Discover is a key of your dictionary. You can access the keys collection in your dictionary using keys() method. Then use each key to access the associated element.

for key in account.keys():
    print(key)
    print(account[key])
Alessandro Da Rugna
  • 4,571
  • 20
  • 40
  • 64
0

if you have more keys, you can loop like this:

for i in account:
    print i
Giordano
  • 5,422
  • 3
  • 33
  • 49
0

It sounds like you want to see the keys of your dict (which in this example is just a single key, 'Discover'). Given a dict key, you can use that key to index into the dict to get the associated value. Here are some examples using the values you gave:

>>> account = {'Discover': ['username', 'dddddd']}
>>> account
{'Discover': ['username', 'dddddd']}
>>> account.keys()
['Discover']
>>> account['Discover']
['username', 'dddddd']
>>>
Tom Karzes
  • 22,815
  • 2
  • 22
  • 41