Stin
Stin

Reputation: 13

Python : Dictionary and .format

could someone help me understand why this works and the latter does not? For instance,

def main():
    diction = {"DDL":"Defined Data Language","EDW":"Enterprise Data Warehouse","ACID": "Atomicity,Consistency,Isolation,Durability"}
    TEST=diction.get("DDL")
    
print(" Meaning:{}".format(TEST))

The above code works however if I make the variable TEST = diction[0] the code fails. Could anyone explain this to me?

P.S. the error is the following

Traceback (most recent call last):
  File "C:\Program Files\Sublime Text\Python_Executables\second_mod.py", line 8, in <module>
    main()
  File "C:\Program Files\Sublime Text\Python_Executables\second_mod.py", line 4, in main
    TEST=diction[0]
KeyError: 0
[Finished in 80ms]

Thank you ahead of time!

Upvotes: 0

Views: 136

Answers (4)

gajendragarg
gajendragarg

Reputation: 471

Python Dictionary items are accessed using key name, index can't be used. In your example, 0 is considered as a key. Since it is not in the dictionary diction, code throw KeyError

Upvotes: 1

John Giorgio
John Giorgio

Reputation: 659

It throws an error because you are trying to get the value of the dictionary identified by the key 0. Yet, you don't have any 0 in your dictionary.

It would work if you included it.

diction = {"DDL":"Defined Data Language",
           "EDW":"Enterprise Data Warehouse",
           "ACID": "Atomicity,Consistency,Isolation,Durability",
            0: 'something'
        }

In conclusion, you can only call elements by their key, if you are dealing with dictionaries in Python, not by their index position, as you would do with a list or tuple. Therefore, the possibilities you have are the following; everything else will fail.

diction['DDL']
diction['EDW']
diction['ACID']

Upvotes: 0

Clumsy
Clumsy

Reputation: 1

Dictionaries are unordered, you can't get key value by index, you can only get key value by key name, example: TEST = diction["DDL"]

Upvotes: 0

eshirvana
eshirvana

Reputation: 24613

because you are dealing with dictionaries and they are made of set of key,values and you can get the value by given keys and not with indexes.

But if you must get a value using index , you can convert the dictionary to list :

TEST = list(diction.values())[0]

Upvotes: 1

Related Questions