Dictionaries vs Lists?


#1

What are the advantages of using a list over a dictionary? A dictionary has more features than a list and makes items more accessible. Why should I use lists?

Any insights would be appreciated.

-C :beginner:

P.S.: Can you use dictionaries in a for loop, as you can with lists?


#2

A list is ordered and contains only items. This is useful in many ways, especially when we wish to retain order, or be able to sort.

A dictionary, on the other hand is not ordered (typically) and works like a lookup table. Look up a key and the value is returned.

# list object

array = [1,2,3,4,5,6,7,8,9]

# dict object

hash = {
    '1': 'one',
    '2': 'two',
    '3': 'three',
    '4': 'four',
    '5': 'five',
    '6': 'six',
    '7': 'seven',
    '8': 'eight',
    '9': 'nine'
}

Yes, using the same operator, as well, in.

for element in array:
    print element

for i in range(len(array)):
    print array[i]

for key in hash:
    print key, ":", hash[key]

#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.