What is the back-end of this situation, where two same keys have different values but the output is little strange? What's going on?
Dictionaries are indexed by Keys. If you store using a key that is already in use, the old value associated with that key is forgotten. It is an error to extract a value using a non-existent key.
Read more about dictionaries in https://docs.python.org/2/tutorial/datastructures.html#dictionaries before using them
an one-line excerpt from python documentation:
If you store using a key that is already in use, the old value
associated with that key is forgotten.
I guess it's easier for you to understand it with some codes here.
d = {'a':'A', 'b':'B', 'a':'C'}
d['a']
# output
'C'
print(d)
# output
{'b':'B', 'a':'C'}
it's not very hard to see that python has deleted the old key value pair for a here and the dictionary itself has only 2 items in it. this is basically what python meant by forgotten.
Related
This question already has answers here:
How do Python dictionary hash lookups work?
(5 answers)
Closed last month.
I have two dictionaries and my objective was to replace the keys in first_dict, with the values in second_dict.
I got the code working, but largely through trial and error, so would like some help understanding and translate exactly what is going on here in Python.
first_dict={"FirstName": "Jeff", "Town": "Birmingham"}
second_dict={"FirstName": "c1", "Town": "c2"}
new_dict = {second_dict[k]: v for k, v in first_dict.items()}
This gives me what I want, a new dict as follows:
{'c1': 'Jeff', 'c2': 'Birmingham'}
How is this working?
"new_dict" creates a new dictionary
so "in first_dict.items()", i.e. for each key-value paid in "first_dict":
the value in the new_dict is the value from "row"
the key in the new_dict is the value from the second_dict
How does "second_dict[k]" do this? it seems like it is doing some sort of a lookup to match between the keys of first_dict and second_dict? Is this right, and if so, how does it work?
Python dictionaries are implemented using hash tables. It is basically an array. To access the array we need indices. The indices are obtained using a hash function on the keys. Hash function tries to distribute the key evenly (property of any hash function - hash functions hate collisions).
When you are creating the last dictionary, it just reads the k and v from the other dictionary and then the value v's become the key of the new dictionary. So yes, the hash function finds out the hashed values and then in that index put the correct value (which is k from other dictionary for you).
Note: How a hashtable handles collision is a separate topic in itself. There are several ways of handling this. One of them is open addressing scheme. You can look that up for further details.
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
Python v3.4.2
I've created a dictionary from a list of keys and stored the number of times the key occurs.
My code works as intended, but I'm unsure WHY it works:
count_dict = {key: key_list.count(key) for key in key_list}
I see that for every key in key_list, I'm adding 'key' and 'count' value pairs to the dictionary. But why does this syntax work? I would expect to need to declare an empty dictionary and then add the key value pairs within a for..in.. loop.
It appears to work for lists as well. But when I try something such as:
print(x) for x in key_list
I get a syntax error.
this is known as a dictionary comprehension
it was introduced in python 2.7
see: https://docs.python.org/2/tutorial/datastructures.html#dictionaries
there are also set comprehensions, list comprehensions, generator statements...
however you are right you cannot just write arbitrary code and expect it to work
ie print(x) for x in key_list is indeed a syntax error
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 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.