Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
For example I have two dicts:
a = {'a':1,'b':0, 'c':5}
b = {'d':4,'a':2}
While update() function can refresh old values, like
a.update(b)
will return
{'a': 2, 'b': 0, 'c': 5, 'd': 4}
but I want to have their sum, in other words, I want to have
{'a': 3, 'b': 0, 'c': 5, 'd': 4}
so the value of 'a' is the sum of both dict
How can I do that?
Following code will update a the way you want:
a = {'a': 1, 'b': 0, 'c': 5}
b = {'d': 4, 'a': 2}
for k, v in b.iteritems():
a[k] = a.get(k, 0) + v
print a # {'a': 3, 'c': 5, 'b': 0, 'd': 4}
collections.Counter might give you what you want. The documentation for collections.Counter.update() says:
Like dict.update() but adds counts instead of replacing them.
from collections import Counter
a = Counter({'a':1, 'b':0, 'c':5})
b = {'d':4, 'a':2}
a.update(b)
print a
Result:
Counter({'c': 5, 'd': 4, 'a': 3, 'b': 0})
Related
This question already has answers here:
How to insert key-value pair into dictionary at a specified position?
(8 answers)
Closed 1 year ago.
I have dictionary like below:
data = {'a': 1, 'c': 2, 'd': 3}
Is there any way to update my above dictionary after particular key? For example you want to add 'b':4 after 'a':1, and at the end add 'E':6 — so final output map should look like below:
data = {'a': 1, 'b':4, 'c': 2, 'd': 3, 'E':6}
I have gone through some documentation but I did not find any reference where we can update dictionary at particular position.
May this solve your problem and the return value is also dict not list
import operator
data = {'a': 1, 'c': 2, 'd': 3}
data['b'] = 4
data['e'] = 6
sorted_d = dict(sorted(data.items(), key=operator.itemgetter(0)))
Output
{'a': 1, 'b': 4, 'c': 2, 'd': 3, 'e': 6}
For example, you updated your data dict with like this below:
data = {'a': 1, 'd': 3, 'c': 2, 'e':6, 'b':4}
Then you can do something like this:
# x[0] is referring to the key here. if you want to sort based on the value
# then it will be x[1]
sort_orders = dict(sorted(data.items(), key=lambda x: x[0]))
which will give:
{'a': 1, 'b': 4, 'c': 2, 'd': 3, 'e': 6}
Note: this might be case sensitive while sorting the order.
This question already has answers here:
How do I create a nested dict from a dict by splitting the keys on a delimiter in python?
(4 answers)
Closed 1 year ago.
I want to write a method which takes a dict in the form of {a: 1, b-c: 2, b-d: 3, e-f-g: 4} and returns {a: 1, b: {c: 2, d: 3}, e: {f: {g: 4}}}. Basically split the keys containing - into subdicts. I've tried to do it iteratively and recursively but I got stuck. Any tips?
You can use collections.defaultdict with recursion:
from collections import defaultdict
d = {'a': 1, 'b.c': 2, 'b.d': 3, 'e.f.g': 4}
def group(d):
nd = defaultdict(list)
for [a, *b], c in d:
nd[a].append([b, c])
return {a:b[0][-1] if not any(j for j, _ in b) else group(b) for a, b in nd.items()}
result = group([[a.split('.'), b] for a, b in d.items()])
Output:
{'a': 1, 'b': {'c': 2, 'd': 3}, 'e': {'f': {'g': 4}}}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
this is a list, I got lists like this :
k = [{a:1}, {b:2}, {c:3}, {d:4}, {a: 5}] and t = [{a:6}, {b:7}, {c:8}, {d:9}, {a: 10}]
if a's dictionary key in k is matching with t's dictionary key in t, then extract value and key in dictionary
and then I want to reorganize like below:
newlist = [a is 1 and 6, b is 2 and 7, c is 3 and 8, d is 4 and 9, a is 5 and 10]
From your description, it is little hard to understand what you require exactly, but I have done my best to obtain what I think you need! :-)
k = [{'a':1}, {'b':2}, {'c':3}, {'d':4}, {'a': 5}]
t = [{'a':6}, {'b':7}, {'c':8}, {'d':9}, {'a': 10}]
newlist = []
for i in range(min(len(k), len(t))):
letter_k, value_k = [*k[i].items()][0]
letter_t, value_t = [*t[i].items()][0]
if letter_k == letter_t:
newlist.append({letter_k: [value_k, value_t]})
This will yield:
newlist = [{'a': [1, 6]}, {'b': [2, 7]}, {'c': [3, 8]}, {'d': [4, 9]}, {'a': [5, 10]}]
Note that I did not combine the dictionaries due to duplicate keys!
Suppose I have the following dictionary:
{'a': 0, 'b': 1, 'c': 2, 'c.1': 3, 'd': 4, 'd.1': 5, 'd.1.2': 6}
I wish to write an algorithm which outputs the following:
{
"a": 0,
"b": 1,
"c": {
"c": 2,
"c.1": 3
},
"d":{
"d": 4,
"d.1": {
"d.1": 5,
"d.1.2": 6
}
}
}
Note how the names are repeated inside the dictionary. And some have variable level of nesting (eg. "d").
I was wondering how you would go about doing this, or if there is a python library for this? I know you'd have to use recursion for something like this, but my recursion skills are quite poor. Any thoughts would be highly appreciated.
You can use a recursive function for this or just a loop. The tricky part is wrapping existing values into dictionaries if further child nodes have to be added below them.
def nested(d):
res = {}
for key, val in d.items():
t = res
# descend deeper into the nested dict
for x in [key[:i] for i, c in enumerate(key) if c == "."]:
if x in t and not isinstance(t[x], dict):
# wrap leaf value into another dict
t[x] = {x: t[x]}
t = t.setdefault(x, {})
# add actual key to nested dict
if key in t:
# already exists, go one level deeper
t[key][key] = val
else:
t[key] = val
return res
Your example:
d = {'a': 0, 'b': 1, 'c': 2, 'c.1': 3, 'd': 4, 'd.1': 5, 'd.1.2': 6}
print(nested(d))
# {'a': 0,
# 'b': 1,
# 'c': {'c': 2, 'c.1': 3},
# 'd': {'d': 4, 'd.1': {'d.1': 5, 'd.1.2': 6}}}
Nesting dictionary algorithm ...
how you would go about doing this,
sort the dictionary items
group the result by index 0 of the keys (first item in the tuples)
iterate over the groups
if there are is than one item in a group make a key for the group and add the group items as the values.
Slightly shorter recursion approach with collections.defaultdict:
from collections import defaultdict
data = {'a': 0, 'b': 1, 'c': 2, 'c.1': 3, 'd': 4, 'd.1': 5, 'd.1.2': 6}
def group(d, p = []):
_d, r = defaultdict(list), {}
for n, [a, *b], c in d:
_d[a].append((n, b, c))
for a, b in _d.items():
if (k:=[i for i in b if i[1]]):
r['.'.join(p+[a])] = {**{i[0]:i[-1] for i in b if not i[1]}, **group(k, p+[a])}
else:
r[b[0][0]] = b[0][-1]
return r
print(group([(a, a.split('.'), b) for a, b in data.items()]))
Output:
{'a': 0, 'b': 1, 'c': {'c': 2, 'c.1': 3}, 'd': {'d': 4, 'd.1': {'d.1': 5, 'd.1.2': 6}}}
This question already has answers here:
Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?
(22 answers)
Closed 5 years ago.
How to add the values of two dictionary ?
Ex :
a = {'a':10,'b':11,'c':20}
b = {'a':1,'b':1,'c':1}
result must be
c = {'a':11,'b':12,'c':21}
You can easily add two dictionaries by using Counter class of collections library for ex:
from collections import Counter
a = {'a':10,'b':11,'c':20}
b = {'a':1,'b':1,'c':1}
a = Counter(a)
b = Counter(b)
c = dict(a + b)
print c
OUTPUT
{'c': 21, 'b': 12, 'a': 11}
Next some please show some effort..
a = {'a':10,'b':11,'c':20}
b = {'a':1,'b':1,'c':1}
c = {k: a[k] + b[k] for k in a}
print(c) # {'c': 21, 'b': 12, 'a': 11}
The above works fine if we assume that a and b have the same keys.
If that is not the case, you can try the following:
a = {'a': 10, 'b': 11, 'c': 20, 'h': 5}
b = {'a': 1, 'b': 1, 'c': 1, 'd': 12}
all_keys = set(a.keys()) # in Python 3 it can be simplified as `all_keys = set(a)`
all_keys.update(b.keys()) # in Python 3 it can be simplified as `all_keys.update(b)`
c = {k: a.get(k, 0) + b.get(k, 0) for k in all_keys}
print(c) # {'c': 21, 'h': 5, 'a': 11, 'b': 12, 'd': 12}
Notice that i am using get on both dictionaries to skip the check on the existence of the key.