How to update a dictionary at specific positions? [duplicate] - python

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.

Related

Adding to a dictionary based on key and value from lists?

I have a dictionary defined as:
letters = {'a': 2, 'b': 1, 'c': 5}
I want to add values to this dictionary based on two lists: one which contains the keys and another which contains the values.
key_list = [a, c]
value_list = [2, 5]
This should give the output:
{a: 4, b: 1, c: 10}
Any ideas on how I can accomplish this? I am new to working with the dictionary structure so I apologise if this is extremely simple.
Thanks.
You can zip the two lists and then add to the dictionary as so;
letters = {'a': 2, 'b': 1, 'c': 5}
key_list = ['a', 'c']
value_list = [2, 5]
for k,v in zip(key_list, value_list):
letters[k] = letters.get(k, 0) + v
Using the dictionary's get() method as above allows you to add letters that aren't already in the dictionary.
for i in range(len(key_list)):
letters[key_list[i]] += value_list[i]
You can simply add or modify values from a dictionary using the key
For example:
letters = {'a': 2, 'b':1 , 'c': 5}
letters['a'] += 2
letters['c'] += 5
print(letters)
output = {'a': 4, 'b': 1, 'c': 10}

Python Find permutable list in a dict list

Given
listOfDict = [{'ref': 1, 'a': 1, 'b': 2, 'c': 3},
{'ref': 2, 'a': 4, 'b': 5, 'c': 6},
{'ref': 3, 'a': 7, 'b': 8, 'c': 9}]
Lets' consider a list of permutable integer
[7,8,9]=[7,9,8]=[8,7,9]=[8,9,7]=[9,7,8]=[9,8,7] # (3!)
Each of this list has a unique mapping ref, so how given for (8,7,9) can I get ref=3 ?
Also in real case I might until 10 (a,b,c,d,e,f,g,h,i,j)...
You can generate a dictionary that maps the values as frozenset to the value of ref:
listOfDict = [{'ref': 1, 'a': 1, 'b': 2, 'c': 3},
{'ref': 2, 'a': 4, 'b': 5, 'c': 6},
{'ref': 3, 'a': 7, 'b': 8, 'c': 9}]
keys = ['a', 'b', 'c']
out = {frozenset(d[k] for k in keys): d['ref'] for d in listOfDict}
# {frozenset({1, 2, 3}): 1,
# frozenset({4, 5, 6}): 2,
# frozenset({7, 8, 9}): 3}
example:
check = frozenset((8,7,9))
out[check]
# 3
but I don't know in advance the name of the other keys!
Then use this approach:
out = {}
for d in listOfDict:
d2 = d.copy() # this is to avoid modifying the original object
out[frozenset(d2.values())] = d2.pop('ref')
out
or as a comprehension:
out = dict(((d2:=d.copy()).pop('ref'), frozenset(d2.values()))[::-1]
for d in listOfDict)
Here is a commented solution to your problem. The idea is to compare the sorted list of the values in a, b, c etc with the sorted values in list_of_ints. The sorted values will be the same for all permutations of a given set of numbers.
def get_ref(list_of_ints):
# Loop through dictionaries in listOfDict.
for dictionary in listOfDict:
# Get list of values in each dictionary.
vals = [dictionary[key] for key in dictionary if key != "ref"]
if sorted(vals) == sorted(list_of_ints):
# If sorted values are equal to sorted list of ints, return ref.
return dictionary["ref"])
By the way, I believe it would be cleaner to structure this data as a dict of dicts in the following way:
dicts = {
1: {'a': 1, 'b': 2, 'c': 3},
2: {'a': 4, 'b': 5, 'c': 6},
3: {'a': 7, 'b': 8, 'c': 9}
}
The code would then be:
def get_ref(list_of_ints):
for ref, dictionary in dicts.items():
if sorted(dictionary.values()) == sorted(list_of_ints):
return ref
Assuming that all integers in the permutations are unique, the code can be simplified further using sets instead of sorted lists.
Since its a list of dict I can call each dict as it self by using for loop
and record the first number on ref
for i in listOfDict:
ref_num=i["ref"]
and to turn dictunary to list we simply use:
z=list(i.values())
then the last step is to find if its the same input list if so we print/return the ref number
if z[1:]==InputList:
return ref_num
and the code should be like this:
listOfDict = [
{"ref": 1,
"a": 1,
"b": 2,
"c": 3},
{"ref": 2,
"a": 4,
"b": 5,
"c": 6},
{"ref": 3,
"a": 7,
"b": 8,
"c": 9},]
def find_ref_Num(InputList):
for i in listOfDict:
ref_num=i["ref"]
z=list(i.values())
if z[1:]==InputList:
return ref_num
print ("your ref number is: "+str(find_ref_Num([7,8,9])))

Nesting dictionary algorithm

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}}}

How to multiple values of keys with different numbers in dictionary?

Im trying to multiple some values from dictionary
example
price_list = {'a': 3, 'b': 2, 'c': 5, 'd': 10}
when i type
total=sum(price_list.values())
print("Total sum is ",total)
it result 20
But now i want to multiple a with 3, b with 5, c with 2 and d with 3 and my desired output to be 59. What is easiest way to do that?
Assuming your numbers are stored in the list, iterate through the values, and multiply with your required number like so
price_dict = {'a': 3, 'b': 2, 'c': 5, 'd': 10}
numbers_dict = {'a': 3, 'b': 5, 'c': 2, 'd': 3}
result = 0
for key, value in price_dict.items():
result += numbers_dict[key] * value
print(result)
#59
You can just perform operations on the dictionary item like you would any other variable:
# multiply 'a' by 3
price_list['a'] *= 3
Try this:
price_list = {'a': 3, 'b': 2, 'c': 5, 'd': 10}
numbers = [3,5,2,3]
for k,n in list(zip(price_list, numbers)):
price_list[k] *= n
then the price list will change, you can use sum as you did to calculate the result.

How to add values from different dict based on their key [closed]

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})

Categories