Error slicing list of dictionaries by key? - python

I have a Pandas Series which contains dictionaries holding two key-value pairs each.
Here is a picture of the data (apologies for size)
How would I go about getting all of the 'C' key's values, like [10000000.0, 3162277.66 ..., 1000000.0, ...] here? I've already tried sorted_combos.iloc[:, 0]['C'], but that gives me a KeyError, so I am stumped.
How am I do to this for future reference? Thank you all in advance.

You can try using a list comprehension to loop over all the dictionaries. In this case, the code would be [dic['C'] for dic in sorted_combos.iloc[:,0]].

Related

Understanding Python dictionary "lookups" between dictionaries to replace keys [duplicate]

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.

indexing nested dictionary elements

I am trying to access the dictionary elements in python, which looks like this:
mydict= {'message':'','result':[{'abc':1,'xyz':2}]}
I want to access the value of key 'xyz'.Is there any direct method to access it in python.
Any help is greatly appreciated.
In steps,
mydict['result'] returns [{'abc':1,'xyz':2}]
mydict['result'][0] returns {'abc':1,'xyz':2}
mydict['result'][0]['xyz'] returns 2
The answer above is wrong in that mydict['result'][0] doesn't work because you don't index dictionaries like a list.
To access 1, you must use the actual string in the key of the nested dictionary: mydict['result']['abc']

How do I sort a list in a dictionary

How can I sort the list present in the dictionary:
fourB={"James":[10,11,9]}
I will have multiple entries but I want to be able to sort the list of integers out for each one of them. How can I do that? Thanks!Any help will be appreciated. :)
for numbers in fourB.values():
numbers.sort()
The above is better than iterating over the keys() followed by indexing into fourB, because here you avoid the dict lookup.
If you love one-liners, here's one:
map(list.sort, fourB.values())
But take note if there are many keys in the dict, as this will return a list of [None]*len(fourB.values()) which is immediately discarded--and that's not optimally efficient. I'd stick with the obvious loop version for this reason and also for readability.
You should iterate over the keys and sort their values:
for k in fourB.keys():
fourB[k].sort()

How to set value in python dictionary while looking it up from another dictionary?

I have two dictionaries. The first is mapping_dictionary, it has several key-value pairs. It will serve as a reference. The second dictionary only has two key-value pairs. I would like to look up the value that should be assigned to the second dictionary in the mapping_dictionary and set it to one of the values. I tried doing it a few different ways but no success.
Please let me know if the syntax is wrong or if this is not the way to do something like this in Python? Thank you in advance for any help.
Example 1:
mapping_dictionary={'TK_VAR_DEC':1, 'TK_ID':2, 'TK_COMMA':3}
token_dictionary={'TK_TYPE', 'TK_VALUE'}
tk_v=mapping_dictionary.get("TK_VAR_DEC")
token_dictionary['TK_TYPE']=tk_v
token_dictionary['TK_VALUE']="VAR_DEC"
Example 2:
token_dictionary['TK_TYPE']=mapping_dictionary.get("TK_VAR_DEC")
token_dictionary['TK_VALUE']="VAR_DEC"
With the definition of the token_dictionary, you're not defining a dictionary at all -- you've written the literal syntax for a set. You need to specify values for it to be a dictionary. I expect that if you change to using token_dictionary = {'TK_TYPE': None, 'TK_VALUE': None} you'll have more luck.
Also note that using .get() is unnecessary for retrieving a value from the dictionary. Just use [].

Sum across all list positions in a dictionary

This is a question and answer I wanted to share, since I found it very useful.
Suppose I have a dictionary accessible with different keys. And at each position of the dictionary I have a list of a fixed length:
a={}
a["hello"]=[2,3,4]
a["bye"]=[0,10,100]
a["goodbye"]=[2,5,50]
I was interested to compute the sum across all entries in a using only position 1 of their respective lists.
In the example, I wanted to sum:
finalsum=sum([3,10,5]) #-----> 18
Just skip the keys entirely, since they don't really matter.
sum(i[1] for i in a.itervalues())
Also as a side note, you don't need to do a.keys() when iterating over a dict, you can just say for key in a and it will use the keys.
You can use a.values() to get a list of all the values in a dict. As far as I can tell, the keys are irrelevant. a.itervalues() works by iterating rather than constructing a new list. By using this, and a generator expression as the argument to sum, there are no extraneous lists created.
I used list-comprehensions for my one line solution(here separated in two lines):
elements=[a[pos][1] for pos in a.keys()] #----> [3,5,10]
finalsum=sum(elements)
I'm happy with this solution :) , but, any other suggestions?

Categories