Python - Using dictionaries to simulate flexible lists: Integer keys

Introduction

By using integer keys, dictionaries can emulate lists that seem to grow on offset assignment:

Demo

D = {} 
D[99] = 'test' #  w w w.j  a  v  a2  s .  c  o m
print( D[99] )
print( D )

Result

Here, it looks as if D is a 100-item list, but it's really a dictionary with a single entry.

The value of the key 99 is the string 'test'.

You can access this structure with offsets much like a list, catching nonexistent keys with get or in tests if required.

You don't have to allocate space for all the positions.

You might employ integer keys in our movie database's code to avoid quoting the year.

Demo

table = {1975: 'Database', 
         1979: 'Json',              # Keys are integers, not strings 
         1983: 'The Web'} 
print( table[1975] )
print( list(table.items()) )

Result

Related Topic