Combining list with dictionary


#1

HI,
So I am trying to combine the use of lists with dictionaries.

board = [1,3,5]
converter_to_letters = {
‘0’: 0,
‘01’: 1,
‘10’: 2,
‘11’: 3,
‘20’: 4,
‘21’: 5,
}
for board in converter_to_letters:
print (board)

As you can see, I am trying to convert the numbers in a given list to binary and print them out.
I thought of creating a dictionary and then applying the numbers in the list to match those of the dictionary.
It seemed like a good idea but I cant get it to actually print the conversion of only the list values to binary .
any ideas?
Thanks


#2

dict class objects have three methods for extracting information:

dict.items()

will return a list of tuples containing the key, value pairs.

dict.keys()

will return a list-like object of the keys. I say list-like because it can be iterated but not subscripted.

dict.value()

will return a list of the values.

>>> converter_to_letters.items()
dict_items([('1', 1), ('10', 2), ('100', 4), ('101', 5), ('11', 3), ('0', 0)])
>>> converter_to_letters.keys()
dict_keys(['1', '10', '100', '101', '11', '0'])
>>> converter_to_letters.values()
dict_values([1, 2, 4, 5, 3, 0])
>>> keys = converter_to_letters.keys()
>>> keys[0]
Traceback (most recent call last):
  File "<pyshell#253>", line 1, in <module>
    keys[0]
TypeError: 'dict_keys' object does not support indexing
>>> items = converter_to_letters.items()
>>> items[0]
Traceback (most recent call last):
  File "<pyshell#255>", line 1, in <module>
    items[0]
TypeError: 'dict_items' object does not support indexing
>>> values = converter_to_letters.values()
>>> values[0]
Traceback (most recent call last):
  File "<pyshell#257>", line 1, in <module>
    values[0]
TypeError: 'dict_values' object does not support indexing
>>> 

As we can see, none of these lists are subscriptable.


#3

How would I then assign the conversions to binary to a new list using append?


#4

Perhaps this is not a good example since it is ordered, and not really something we would use a dictionary for. Dictionaries are for data that is unordered, to start with.

What you want is simply a function that return a binary when you input an integer, or an integer when you input a binary.

>>> def int_to_bin(n):
    return bin(n)

>>> int_to_bin(17)
'0b10001'
>>> def bin_to_int(n):
    return int(n, 2)

>>> bin_to_int('0b10001')
17
>>>