-1

I'm trying to iterate all elements in map(dictionary). But I'm getting this error. Why does it say dict as list? And how do we resolve this problem?

'list' object has no attribute 'items' on line 13 in main.py

def thirdfarthestdistance(arr,x):
  map = {}
  for elem in arr:
    # Storing {(5, -3), (distance, element)}
    map[abs(elem-x)] = elem

  map = sorted(map)
  count = 0

  for key, value in map.items: # I tried map.items() too but didn't work.
    print(value)
    # if count == 2:
    #   return elem
    count = count + 1

print(thirdfarthestdistance([-3, -2, -1, 4, 7], 2))
merry-go-round
  • 4,533
  • 10
  • 54
  • 102
  • 3
    `sorted` returns a list. dicts are unordered mappings, they can't be sorted. Use a `collections.OrderedDict` instead. Also, `for key, value in map.items:` should be `for key, value in map.items():`. – Aran-Fey Mar 25 '18 at 17:32
  • 2
    Possible duplicate of [How can I sort a dictionary by key?](https://stackoverflow.com/questions/9001509/how-can-i-sort-a-dictionary-by-key) – Aran-Fey Mar 25 '18 at 17:32
  • No I tried items() too and it returns same error. You can try it on Code Playground (https://trinket.io/python/ffe3531e69) – merry-go-round Mar 25 '18 at 17:33

2 Answers2

3

The problem lies in the sorted(...) method. From python documentation:

https://docs.python.org/3/library/functions.html#sorted

You'll see that the method returns a list. Therefore, when you call

map = sorted(map)

You are actually converting your dictionary to a sorted list.

Off the top of my head, a better way of doing this would be getting a sorted list of the keys, and then referencing that. Something like

keys = sorted(map.keys()) 
print(map[keys[2])

Obviously this is not including validation on your initial array.

Michael S
  • 166
  • 2
  • 7
1

sorted returns a list; you are replacing your dict with the list of sorted keys.

Instead, you just want

for key, value in sorted(map.items()):

which iterates over a list of key/value pairs sorted by key.

chepner
  • 497,756
  • 71
  • 530
  • 681