Copying a list one collection to another collection - python

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 (==).

Related

Python Search Dictionary by Key to return Value

I have a fairly complex dictionary with lists that I'm trying to use. I'm attempting to search the dictionary for the key "rows", which has a list.
With my current sample of data, I can easily pull it like so with index operator:
my_rows = my_dict['inputContent']['document']['fields'][2]['value']['rows']
'rows' is a list and those are the values I am trying to pull. However, my data from 'rows' won't always be in the exact same location but it will always be in my_dict. It could be in a different index like so:
my_dict['inputContent']['document']['fields'][4]['value']['rows']
or
my_dict['inputContent']['document']['fields'][7]['value']['rows']
Really any number.
I've tried using just the basic:
my_rows = my_dict.get("rows")
But this returns None.
I find lots of articles on how to search for values and return key, but I know the key and it will always be the same, while my values in 'rows' will always be different.
I'm new to python and using dictionaries in general, but i'm really struggling to drill down into this dictionary to pull this list.
my_dict['inputContent']['document']['fields'][2]['value']['rows']
my_dict['inputContent']['document']['fields'][4]['value']['rows']
my_dict['inputContent']['document']['fields'][7]['value']['rows']
Looks like the overall structure is the same, the only variable is the numeric list index of the fourth element. So we need a loop that iterates over each element of that list:
for element in my_dict['inputContent']['document']['fields']:
if 'rows' in element['value']:
# found it!
print(element['value']['rows'])

get item from dict and count number of items in the list

I used jsondiff.diff() to compare the flattened items (as a json) from two jsons of the mapping of an Elasticsearch index. One is what I loaded, the original mapping I created, and the other is the mapping queried from Elasticsearch, so it could technically be different if the data inserted was different from expected.
The mappings are identical, so to test finding the diff I added 2 different fields to the original mapping.
Using jsondiff.diff() works beautifully, and I find my differences.
diff(dfpulledlist, dfloadedlist)
diff(dfloadedlist, dfpulledlist)
That produces:
{insert: [(114, 'mappings.properties.saw_something.properties.monster_fish'), (121, 'mappings.properties.aliens')]}
It looks like a dictionary. Type() tells me it is a <class 'dict'>, but trying to get the items under insert gives me errors. I therefore printed the items and found something strange. Now I'm trying to figure out how to get to the items of insert so I can count them and don't know how to work my way through this.
print(diff_pulled_to_loaded.items())
Gives me:
dict_items([(insert, [(114, 'mappings.properties.saw_something.properties.monster_fish'), (121, 'mappings.properties.aliens')])])
Looking at this page, it looks like it is a dictionary from sequence having each item as a pair. I can't access it as a dictionary though. dict['insert'] or dict.insert . On each attempt I get KeyError: 'insert'.
How do I get to the values of insert, which is an array or list of tuples, so I can query that information? What am I missing/misunderstanding here? I want to get to this:
[(114, 'mappings.properties.saw_something.properties.monster_fish'),
(121, 'mappings.properties.aliens')]
It's a dictionary, but keys like insert and replace are not strings, they're instances of the jsondiff.Symbol class. That's why they don't have quotes around them -- this class has a custom representation that just returns the symbol name.
So to access it I think you have to use
d = diff(dfpulledlist, dfloadedlist)
print(d[jsondiff.insert])

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

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

Categories