0

I'm trying to convert key value pairs from a csv file to a dictionary. I've used csv reader and also tried doing it manually using python alone. For some reason, whenever I print out the dictionary, it only outputs the final line. I've even tried creating separate test lists and reloaded my notebook but I still only get the final line. This is my testing code

listOfStrings = ['Hi'] * 300                  # CSV file has about 300 lines
listOfNum = [5] * 300

myDict=dict(zip(listOfStrings, listOfNum))

print(myDict)

I only get

{'Hi':5}

But when I print listOfStrings and listOfNum I get the full output of 300 in each list.

Things like this work:

listOfStrings = ['Hi', 'Hello']
listOfNum = [5, 6]

myDict=dict(zip(listOfStrings, listOfNum))

print(myDict)
{'Hi': 5, 'Hello': 6}
catzen
  • 75
  • 8
  • Dictionaries are not ordered. You want an OrderedDict. – tobias Mar 27 '21 at 18:21
  • Python 3.6+ Dictiinaries are ordered. Your problem is with `keys`. You cannot have duplicate – Prayson W. Daniel Mar 27 '21 at 18:24
  • A dictionary cannot have more than one key that is the same, let alone 300 of them. Your dictionary has only one item, so when you print it you see one item. – kaya3 Mar 27 '21 at 18:24
  • Afaik that's an implementation detail. – tobias Mar 27 '21 at 18:25
  • @tobias No, they updated the language spec in 3.6. – Barmar Mar 27 '21 at 18:25
  • In your first example, you have one key, i.e., 'Hi'. In your second, two, 'Hi' and 'Hello'. So, what you get when printing your dict is expected. – Nikolaos Chatzis Mar 27 '21 at 18:26
  • 1
    @tobias It is not an implementation detail: it is stated in [the docs](https://docs.python.org/3/library/stdtypes.html#mapping-types-dict) that *"Dictionaries preserve insertion order."*, so programs can rely on this behaviour. But this question has **absolutely nothing to do** with dictionary order, it is because dictionary keys cannot be duplicates. – kaya3 Mar 27 '21 at 18:27
  • You're right it is updated in Python 3.7 as per this answer (unless you want to rely on CPython implementation details): https://mail.python.org/pipermail/python-dev/2017-December/151283.html – tobias Mar 27 '21 at 18:28
  • @kaya3 Sorry dear Sir, you'll have to excuse us peasants for commenting. – tobias Mar 27 '21 at 18:30
  • 1
    @tobias You are allowed to write comments, just as I am allowed to write comments that correct yours. There is no need to make this about ego; your comments contain inaccurate information which is also irrelevant to the question, it is not about you or me, it is a matter of collaborating to write useful, relevant information that can help people. – kaya3 Mar 27 '21 at 18:33
  • @kaya3 You're **absolutely** right. Sorry. – tobias Mar 27 '21 at 18:35

1 Answers1

1

Dictonaries in Python do not allow duplicate keys. Becauce all your keys and values are the same, only 1 key will get added to the dictionary.

Seppeke
  • 143
  • 7