1

I'm learning about dictionaries and I wrote a small bit of code and built it.

from collections import OrderedDict

d1 = OrderedDict([('a',0),('b',9),('c',8),('d',7),('e',6)])
d2 = OrderedDict([(1),(2),(3),(4),(5)])

I get the following error:

d2 = OrderedDict([(1),(2),(3),(4),(5)])
TypeError: 'int' object is not iterable

I don't understand why it isn't iterable? And what has 'int' got to do with the problem?

Thanks

Dan
  • 769
  • 2
  • 8
  • 23

3 Answers3

4

As documented here you need to provide key-value pairs to OrderedDict.

At its core, OrderedDict is a dictionary and thus needs a value to store at a key. Passing it (1) is wrong because:

>>a = (1)
>>type(a)
<class 'int'>

So, (1) is not a tuple but an integer object.

xssChauhan
  • 2,728
  • 2
  • 25
  • 36
3

OrderedDicts (or any sub-class of dict for that matter) are a set of key-value pairs.

>>> d1 = OrderedDict([('a',0),('b',9),('c',8),('d',7),('e',6)])
>>> d1['b']
9

The following statement does not provide any such pairs.

d2 = OrderedDict([(1),(2),(3),(4),(5)])

Also note that
(1) is an int.
(1,) is a tuple.

frederick99
  • 1,033
  • 11
  • 18
1

The list elements should be a tuple of 2 items (one key and another value).

(1) becomes 1 an int. So what python is doing is it is trying to split it into key-value pair. So you get that error.

Shreyash S Sarnayak
  • 2,309
  • 19
  • 23