indexing nested dictionary elements - python

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']

Related

Logic behind accessing dictionary values in python

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

Error slicing list of dictionaries by key?

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]].

How to access the list inside dictionary in python?

I have dict structure as shown in image.I am want to access wavelength list values of it.
How to access it or store the wavelength list in another variable.
This should simply be:
dict['wavelength']
Where "dict" is your dictionary name; which looks like it's "n2" maybe. The returned value will be the list that you're looking for.

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 [].

Copying a list one collection to another collection

i have a document in collection coll1 in this form:
{_id: 1, "value" : {"listOfNumbers" : [1,2,3]}}
I would like to know, how can I copy this list into an existing list of collection coll2 using pymongo.
I found this query which will replace the existing list of coll2 with the list [3,2,1]:
db.coll2.update({_id:1}, {$set: {'value.listOfNumbers' : [3,2,1]}})
The problem is, I don't know how to get the list of coll1.
Also, what would be the easiest way to check if the two lists are the same?
I thank you in advance for your replies and your effort to help.
coll1 for me seems to be a simple dictionary, where it should be easy to get the value of the keyword 'value' via
coll1['value']
As the entry is another dictionary, you should be able to get the list via
coll1['value']['list of numbers']
For comparison, it depends on the fact, that lists are only equal in python, if the order and the value of the elements is equal. That should be easy to check with isequal (==).

Categories