DEV Community

Discussion on: Data Structures in Python: Dictionaries

Collapse
 
gbm001 profile image
Andrew McLeod • Edited

Firstly, you rarely use the 'get' method for dictionaries. Normally you just use the square bracket notation for reading value. In your case, temporarily ignoring that it might be better to use 'get' with a default argument you could do:


if node_name in computer_list:
    print (computer_list[node_name])
else:
    print("Please use a designated computer for this program")

Secondly, dictionaries do not have numeric indexes. They also do not have a defined order anyway. Enumerate takes an iterable (such as what is returned by dict.items()) and returns a list of (index, item) tuples. But you can't use the index returned from enumerate on a dictionary.items to access the dictionary items. You can't even guarantee that running it twice will produce the same order of items: because items are dictionaries are unordered.

It is also a lot less repetitive to just say:

my_dict = {key1: value1,
           key2: value2,
           key3: value3}

rather than making repeated

my_dict[keyN] = valueN

assignments.
Finally you haven't said whether you are doing python 2 or python 3 (which has been out for 10 years now...). In python 2 dict.items will return a list of (key, value) tuples (which you can loop over as you do. In python 3 items returns a generator object (like iteritems in python 3). You can still loop over this, but if you want the list of (key, value) tuples you have to call list(dict.items). This is a common source of confusion for people switching from python 2 to python 3...
Finally finally you should probably say that dictionary keys can be any hashable object - e.g. integers, floats (although that is a bad idea), strings, tuples and user-defined classes.

Collapse
 
georgeoffley profile image
George Offley • Edited

I updated the enumeration section. Thanks a lot for your input. On the rest the print() method is usually my tip off on Python2 or 3. While I understand that there can be confusion, anything made in the last year or so should be in Python 3. Anything I write is in Python3 and tested in Python3.

The rest is really style, and there's no substance in writing out adding entries to a dictionary one way or the other. I will say that not repeating yourself is a golden rule in programming. However, for this purpose it doesn't matter.

Finally the get function is only rare if I use it rarely. Unless there is a specific performance issue with using that particular function, I don't think it matters. Thanks for the input, though.