Element-wise addition of lists nested in two dictionaries (Python) - python

I have two dictionaries, and the value for every key is a list of two elements, something like this:
dict1 = {1234: [40.26, 4.87], 13564 [30.24, 41.74], 523545 [810.13, 237.94]}
dict2 = {1231: [43.26, 8.87], 13564 [904.71, 51.81], 52234 [811.13, 327.35]}
I would like to get something like this:
dict3 = {1234: [40.26, 4.87], 1231: [43.26, 8.87], 13564 [934.95, 93.55], 523545 [810.13, 237.94], 52234 [811.13, 327.35]}
So far I have tried many things, but no luck.
Does anybody know the answer for this element-wise addition?

Copy one of the dictionaries to the result. Then loop through the other dictionary, creating or adding to the corresponding key in the result.
from copy import deepcopy
dict3 = deepcopy(dict1)
for key, value in dict2.items():
if key in dict3:
dict3[key] = [value[0] + dict3[key][0], value[1] + dict3[key][1]]
else:
dict3[key] = value.copy()

Related

How do I access a dictionary inside a list inside a list

I have a data that looks like this
dict1 = [[{'num1':1, 'num2':2, 'num3':3}], [{'num1':4,'num2':5, 'num3':6}]]
How do I go inside the list where it contains the dictionary to select a specific key to display.
I seem to be getting a lot if list index out of range error.
Here's my current code:
for items in dict1:
for index in range(len(dict1)):
print(items[index]['num1'])
It's rather obvious that your dict1 is not a single-depth list, it's a list of list, so iterate it this way:
dict1 = [[{'num1':1, 'num2':2, 'num3':3}], [{'num1':4,'num2':5, 'num3':6}]]
for t in dict1:
obj = t[0]
for key in obj:
print(key,obj[key])

Python Dict : How can I get a ordered difference set from dicts?

I'm trying to get difference set from two dicts below:
dict1 = {'area':1, 'ip':1, 'device_name':1, 'max_value':1, 'min_value':1, 'ave_value':1}
dict2 = {'area':1, 'ip':1, 'device_name':1, 'max_value':1, 'min_value':1, 'ave_value':1, 'res_1':1, 'res_2':1, 'res_3':1, 'res_4':1, 'res_5':1}
And I wanna get ordered result like this:
result = {'res_1', 'res_2', 'res_3', 'res_4', 'res_5'}
I've found a way to get difference set:
result = dict2.keys() - dict1.keys()
But the output is not what I want:
[output:]
{'res_3', 'res_1', 'res_4', 'res_2', 'res_5'}
Unfortunately, It is always been a random order .
You can't store things in a set in order, but you can use a list and easily calculate the difference yourself. Using a list comprehension to do it neatly:
result = [key for key in dict2 if key not in dict1]
key not in dict1 is an O(1) operation so the whole thing is O(n) just like regular set difference.
If you want to get a sorted set, you will have to ressort to a third party library such as Sorted Containers: http://www.grantjenks.com/docs/sortedcontainers/index.html
Sets are unordered. You can either sort it before you store it in the result variable, but then the type will be list.
result = sorted(dict2.keys() - dict1.keys())
Otherwise you can sort it before you use it, so you can keep the type of result as set.
result = dict2.keys() - dict1.keys()
print(sorted(result))

Merging 2 dictionaries in Python but keeping the values

This might be a possible duplicate.
I have 2 dictionaries in this format:
dict1={'id1':'11', 'id2':'12', 'key11':'value11', 'key12':'value12'}
dict2={'id1':'n/a', 'id2':'12', 'key21':'value21', 'key22':'value22'}
Notice that the only common key between the 2 dictionaries is id2. So I want my final dict to be something like this:
dict3={'id1':'11', 'id2':'12', 'key11':'value11', 'key12':'value12', 'key21':'value21', 'key22':'value22'}
Also, notice that on the 2nd dictionary. id1 is missing, but on the final output, dict3 is using the value from dict1 because from id2 we know it's the same dictionary.
And finally, if dict2 has no matching keys with dict1, like this:
dict1={'id1':'11', 'id2':'12', 'key11':'value11', 'key12':'value12'}
dict2={'id1':'n/a', 'id2':'somevalue', 'key21':'value21', 'key22':'value22'}
Can then dict3 be dict2 with the dict1 keys but the values set to 'n/a'?? Like this:
dict3={'id1':'n/a', 'id2':'somevalue', 'key21':'value21', 'key22':'value22', 'id2':'n/a', 'key11':'n/a', 'key12':'n/a'}
I'm traversing 2 lists of dictionaries to do this. So my code so far is this:
for d1 in dlist1:
for d2 in dlist2:
if d1['id1']==d2['id1']:
if d1['id2'] == 'n/a':
d1['id2'] = d2['id2']
d1['key21'] = d2['key21']
# adding the new key-value pairs to dictionary 1, one-by-one and so on ...
In short, I'm either adding new fields to one of the nodes in dlist1 or adding an entirely new node to dlist1.
My question is: Is there a quicker pythonic way to do this? Because my implementation is giving me KeyError's

Iterating through (JSON?) map in Python

I have a datastructure like that:
sample_map= {'key1': {'internal_key1': ['value1']},
'key2': {'internal_key2': ['value2']},
}
I would like to iterate throgh on every line key1 and key2. I would like to get the value of 'internal_key1' and 'value_1'variables.
I tried this way:
for keys in sample_map.keys():
for value in sample_map[keys]:
#get internal_keys and values
How should I do this? Someone maybe could tell me about this data structure and the using?
for item in sample_map.values():
for k, v in item.items():
print k, v
How about the following:
for k,v in sample_map.iteritems():
print k
for k1,v1 in v.iteritems():
print k1,v1[0]
This will print the following:
key2
internal_key2 value2
key1
internal_key1 value1
This is called a dictionary (type dict). It does resemble the JSON structure, although JSON is a format in which a string is built to represent a specific structure of data, and dict is a structure of data (that can be converted to a string in JSON format).
Anyway, this line - for value in sample_map[keys]: is invalid. To get the value linked to a key, you just have to do value = sample_map[keys]. In this example, dicts will be assigned to val. Those will be the inner dicts ({'internal_key1': ['value1']} and so on).
So to access the inner keys, call .keys() of value:
for keys in sample_map.keys():
value = sample_map[keys]:
for internal_key in value.keys():
internal_value = value[internal_key]
Also, when using a for loop, there's no need for dict.keys(), it will be used automatically, so your code could look like:
for keys in sample_map:
value = sample_map[keys]:
for internal_key in value:
internal_value = value[internal_key]

Python dictionary

I am having some trouble understanding this, I have tried to reduce the problem to this set of code
for k in y.keys():
if k in dateDict.keys():
if yearDict[k] in dict1:
dict1[yearDict[k]].extend(y[k])
else:
dict1[yearDict[k]] = y[k]
if yearDict[k] in dict2:
dict2[yearDict[k]].extend(y[k])
else:
dict2[yearDict[k]] = y[k]
else:
continue
I have two dictionaries y and dateDict to begin with. For a matching key for y in dateDict, I am populating two other dictionaries dict1 and dict2, hashed with keys from some other dictionary yearDict. Unfortunately the result are duplicated in dict1 and dict2, I have values repeating themselves. Any idea what could be happening?
Also I notice that this code works as expected,
for k in y.keys():
if k in dateDict.keys():
if yearDict[k] in dict1:
dict1[yearDict[k]].extend(y[k])
else:
dict1[yearDict[k]] = y[k]
else:
continue
If y[k] is a list (which it looks like), the same list will be assigned to everywhere where is it used. Dictionaries do not make copies of the elements when they are assigned, they just keep references to their objects. In your example, both keys in dict1 and dict2 will point to the same object.
Later, when it is modified, the same elements will be appended with the new values, once for each map. To prevent this, you can create a new list when initially assigning:
dictl[yearDict[k]] = list(y[k])
However, it is always good to know the Python standard library. This code could be made much more readable, and without the error, by using collections.defaultdict:
from collections import defaultdict
# This goes wherever the dictionaries
# where initially defined.
dict1 = defaultdict(list)
dict2 = defaultdict(list)
# You can get the value here, no need to search it later.
for k, value in y.items():
if k in dateDict.keys():
# No need to call this everywhere.
new_key = yearDict[k]
# Note the defaultdict magic.
dict1[new_key].extend(value)
dict2[new_key].extend(value)
# No need for the 'continue' at the end either.
When asked for a key that does not exist yet, the defaultdict will create a new one on the fly -- so you don't have to care about initialization, or creating copies of you values.

Categories