I have the following dict
commands = {
'cmd1':"configure terminal",
'cmd2':"router",
'cmd3':"MPLS"
}
when I execute the following code:
`for cmd in commands:
print(cmd)
I always get cmd3 as 1st print, why is that?
I am doing something wrong.
Python dictionaries are unordered. Things will come out of them in some order when you iterate over them, but the order probably will not be the same order in which you added them. This is by design.
You can use collections.orderedDict if you need order. Or, in this case, since the keys are not actually needed, just use a list.
To see what the values are - use sorted on the resulting list of items:
for key,value in sorted(commands.items()):
print(key)
print(value)
print commands[key] # same as line above
Related
Rookie here and I couldn't find a proper explanation for this.
We have a simple dict:
a_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
to loop through and access the values of this dict I have to call
for key in a_dict:
print(key, '->', a_dict[key])
I am saying about
a_dict[key]
specifically. Why python use this convention? Where is a logic behind this? When I want to get values of a dictionary I should call it something like
a_dict[value] or a_dict[values] etc
instead (thinking logically).
Could anyone explain it to make more sense please?
edit:
to be clear: why python use a_dict[key] to access dict VALUE instead of a_dict[value]. LOGICALLY.
according to your question, I think you meant why python does not use index instead of key to reach values in the dict.
Please take note that there are 4 main data container in python, and each for its usage. (there are also other containers like counter and ...)
for example elements of list and tuple is reachable by their indices.
a = [1,2,3,4,5]
print(a[0]) would print 1
but dictionary as its name shows, maps from some objects (keys in python terminology) to some other objects(values in python terminology). so we would call the key instead of index and the output would be the value.
a = { 'a':1 , 'b':2 }
print(a['a']) would print 1
I hope it makes it a bit more clear for you.
I think you are misunderstanding some terminology around dictionaries:
In your example, your keys are color, fruit, and pet.
Your values are blue, apple, and dog.
In python, you access your values by calling a_dict[key], for example a_dict["color"] will return "blue".
If python instead used your suggested method of a_dict[value], you would have to know what your value was before trying to access it, e.g. a_dict["blue"] would be needed to get "blue", which makes very little sense.
As in Feras's answer, try reading up more on how dictionaries work here
Its because, a dictionary in python, maps the keys and values with a hash function internally in the memory.
Thus, to get the value, you've to pass in the key.
You can sort of think it like indices of the list vs the elements of the list, now to extract a particular element, you would use lst[index]; this is the same way dictionaries work; instead of passing in index you would've to pass in
the key you used in the dictionary, like dict[key].
One more comparison is the dictionary (the one with words and meanings), in that the meanings are mapped to the words, now you would of course search for the word and not the meaning given to the word, directly.
You are searching for a value wich you don't know if it exists or not in the dict, so the a_dict[key] is logic and correct
self.PARSE_TABLE={"$_ERROR":self.WEEK_ERRORS,"$_INFORM":self.WEEK_INFORM,"$_REDIR":self.WEEK_REDIRECTS,"$_SERVER_ERROR":self.WEEK_SERVER_ERROR,"$_BYTES":self.WEEK_BYTES,"$_HITS":self.WEEK_HITS}
for j in self.PARSE_TABLE:
print j
break
When I run this on my python the first element I get is S_REDIR can someone explain why?
Dictionaries don't maintain order. The order you get from iterating over them may not be the order in which you inserted the elements. This is the price you pay for near-instant lookup of values by key. In short, the behavior you are seeing is correct and expected, and may even vary from run to run of the Python interpreter.
It normal behaviour. Inside dictionary and set using hash codes. If you want orderd keys use self.PARSE_TABLE.keys.sort(). Also you can use OrderedDict from collection library.
Dictionary by default stores all the keys in its own convenient order rather to the order we gave.
If the order of the keys should be maintained, you can use OrderedDict which came to implementation from the python version 3.0
P.S. I don't think sorting keys would do any help in preserving the order given.
I'm running this code from Dive Into Python:
def buildConnectionString(params):
"""Build a connection string from a dictionary of parameters.
Returns string."""
return ";".join(["%s=%s" % (k, v) for k, v in params.items()])
if __name__ == "__main__":
myParams = {"server":"mpilgrim", \
"database":"master", \
"uid":"sa", \
"pwd":"secret" \
}
print buildConnectionString(myParams)
The book says its output should be:
server=mpilgrim;uid=sa;database=master;pwd=secret
But when I run it it comes out in reverse:
pwd=secret;database=master;uid=sa;server=mpilgrim
Any ideas why?
The fact that it is in exactly reverse order is really just a coincidence. Run the code with a different version/implementation of python and you'll likely get a different ordering. The reason for this is because in python dictionaries are not ordered so the order of the ouput of your function is not well defined. (The order that you put things into the dictionary is not the order that they are yielded as you iterate over the dictionary).
If you want a specific order, you can sort parames.items() using the builtin sorted function (optionally using the key keyword to tell sorted how to sort the items). Another option is to use an OrderedDict from the collections module which appeared in python2.7 (as pointed out by sr2222).
Because you are printing a dictionary, and dictionaries are unordered. The order a dictionary is iterated through is dependent on a number of factors including interpreter type, interpreter version, and OS. If you want it to come out the same order you put it in, you have to use collections.OrderedDict instead. Alternatively, as mgilson said in his answer, you could sort the dictionary contents before printing it, but given that the order you want is not alphabetical, it's probably more trouble than it is worth.
i need help for this case :
m={}
m[1]=1
m[333]=333
m[2]=2
# Result:
{1: 1, 2: 2, 333: 333}
so even when i didn't enter '333' the last, i got this '333' listed in the end of the dictionary when print it out. why is this 'dictionary' doing auto sort? and how disable it? i can creata a function to re-sort to fix the order. but that's not what i want, i just simply want to print and get output order just like the order when i input the data. Is there any good explanation and is there any solution ?
It is not sorting. dict is not ordered at all, so you cannot influence the key order in any way. There is collections.OrderedDict in 2.7 and 3.1+, there is also standalone module for 2.4-2.6.
Items stored in a dictionary do not have any inherent order. The order they are printed out is entirely down to the hash values for each of the keys and the other items in the dictionary.
Long time after this questions was posted, but just for those who land on this page, since 3.6? dictionaries preserve the order that items are added in.
so I am trying to send a packet with some keys that i have put into a dictionary. these need to be printed in a specific order, so I've tried to make a function to reorder them. I assume python is doing something to rearrange in the order I don't want, but i'm not sure why.
I'm currently using this function to try and achieve this.
def array_sort(array, sort): #yeah, it's array cuz i php like that.
ordered = {}
for i in range(0,len(sort)):
if sort[i] in array:
ordered[sort[i]] = array[sort[i]]
keys = array.keys()
return ordered
order = "l5,l4,l3,l2,q,y,k,k3,d1,z,p,c,b,d3,dt,N,n,a,h,v".split(',')
keys = array_sort(infos, order)
for some reason this isn't working, infos is the list of keys in alphabetical order, i'm just not sure why the function is outputting the keys in an odd order. (a first, when 15 should be first :S)
If you know a better way to do this feel free to tell me, I just recently started on python, so I'm not that familiar.
EDIT:
I was able to print the keys in the correct order using this immediately after making the order dictionary. even if it was just output as a string the order would be preserved (for the time being) and you could .split() it again to get the dictionary in the correct order (i think).
for i in range(0, len(order)):
if order[i] in infos:
packet += order[i] + '="' + infos[order[i]] + '" '
Since dictionaries in Python are unordered and all that you need is to output results ordered by the specified rule you can do something like this:
order = "l5,l4,l3,l2,q,y,k,k3,d1,z,p,c,b,d3,dt,N,n,a,h,v".split(',')
for key in order:
print key, infos.get(key)#if infos is your dictionary
Or you can get/pass list instead of dict the following way:
print [(key, infos.get(key)) for key in order]
Python dictionaries are not ordered containers. Take a look at the collections.OrderedDict instead
Python dictionaries order their keys based on its hash, which will make it seem random. I recommend using OrderedDict to get your keys in order.