-2

input

myDict = {
    "Fast" : "In a Quick Manner",
    "Abhishek" : "A student",
     233 : "Abhishek",
    "a" : ["Abhi","Aka"],
    "b" : [ "abhi",1],
    "hey" : [1,2],
    "hii" : (22, 44, 555),
    "nesteddictionary" : {"RAM":1,"SITA":2,"HANUMAN":3}
print(myDict[1])
print(myDict["nesteddictionary"][0])

output nothingg

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41

4 Answers4

0

The items in a dictionary are not indexed. You must use the key to access the value. However, if for some reason you need the second key-value pair in your dictionary this is how you do it.

myDict = {
    "Fast" : "In a Quick Manner",
    "Abhishek" : "A student",
     233 : "Abhishek",
    "a" : ["Abhi","Aka"],
    "b" : [ "abhi",1],
    "hey" : [1,2],
    "hii" : (22, 44, 555),
    "nesteddictionary" : {"RAM":1,"SITA":2,"HANUMAN":3}}
    
print(myDict[list(myDict.keys())[1]])
print(myDict["nesteddictionary"][list(myDict["nesteddictionary"].keys())[1]])

The list(myDict.keys())[1] will give you the element at index 1 of the list containing all the keys in the dictionary.

M Germanos
  • 108
  • 5
0

Dictionaries are unordered collections of key-value pairs

myDict = {
    "Fast": "In a Quick Manner",
    "Abhishek": "A student",
    233: "Abhishek",
    "a": ["Abhi", "Aka"],
    "b": ["abhi", 1],
    "hey": [1, 2],
    "hii": (22, 44, 555),
    "nesteddictionary": {"RAM": 1, "SITA": 2, "HANUMAN": 3}
}

# Accessing dictionary items by keys
print(myDict["Fast"])  # Access by string key
print(myDict[233])     # Access by integer key
print(myDict["nesteddictionary"]["RAM"])  # Access nested dictionary item by keys
0

Python dictionary keys are unordered except that they exist in the order in which they were added.

The most Pythonic way to handle your problem would be to sub-class UserDict.

Something like this:

from collections import UserDict

class Dict(UserDict):
    def __getitem__(self, i):
        key = list(super().keys())[i]
        return super().__getitem__(key)

myDict = {
    "Fast" : "In a Quick Manner",
    "Abhishek" : "A student",
     233 : "Abhishek",
    "a" : ["Abhi","Aka"],
    "b" : [ "abhi",1],
    "hey" : [1,2],
    "hii" : (22, 44, 555),
    "nesteddictionary" : {"RAM":1,"SITA":2,"HANUMAN":3}}

d = Dict(myDict)
print(d[2])

Output:

Abhishek

Note:

Of course this means that you would not be able to access values by key in the normal way using this class. What you would need to do is reference the UserDict's data attribute. For example:

print(d.data['b'])

Output:

['abhi', 1]
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
-1

Firstly your print statements has two issues:

  • print(myDict[1]) will raise a KeyError because there's no key called 1 in the dictionary myDict.
  • Also, for the statement print(myDict["nesteddictionary"][0]), python dictionaries don't support indexing by position. So, this will also raise a KeyError.

To be more clear, why can't you use indices with dictionaries? Because,

  • Dictionaries are optimized for looking up values based on unique keys. This allows for very fast (constant-time on average) lookups regardless of the size of the dictionary, which wouldn't be the case if they were indexed like lists.
  • Before Python 3.7, dictionaries did not guarantee any specific order of their elements. This means that the order in which items were added to a dictionary might not be the order in which they are stored or retrieved. Starting from Python 3.7, dictionaries maintain the insertion order, but this is more of a side effect of the implementation rather than a core feature of the dictionary data type.

If you find yourself frequently needing to access items by index, you might want to reconsider the data structure you're using. Lists or tuples might be more appropriate if order matters. If you need both key-based access and order-based access, then a combination of data structures or using OrderedDict from the collections module might be the solution. This data structure explicitly maintains the order of items.