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 4 years ago.
Improve this question
I need a function to change values within a nested dictionary,
by crawling a list instead of the usual dic[key1][key2] = value
e.g :
IN[0]: dic = {'1': 23, '3': {'a': 'foo', 'b': 67}}
IN[1]: l = ['3', 'a']
IN[2]: func(dic, l , newvalue)
IN[3]: print dic
Expected output :
OUT[4]: dic = {'1': 23, '3': {'a': newvalue, 'b': 67}}
Try this:
def func(dic, keys, value):
for key in keys[:-1]:
dic = dic.setdefault(key, {})
dic[keys[-1]] = value
func(dic, l , newvalue)
print(dic)
This is not good to use unnecessary things like exec and globals().
Related
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 8 months ago.
Improve this question
I have a list l=['a','b','c'] and I want to create a dict that takes these items as keys and then adds a value to it. Such as:
d={ 'a':0, 'b':1, 'c':2 }
How would I be able to this?
There are many ways to create this dictionary. Here is just a few:
>>> dc = dict(zip(ls, range(3)))
>>> dc2 = {v: k for k, v in enumerate(ls)}
>>> dc2
{'a': 0, 'b': 1, 'c': 2}
>>> assert dc == dc2
>>> # silence because they're same
l=['a','b','c']
d = dict(zip(l,range(len(l))))
print(d) # {'a': 0, 'b': 1, 'c': 2}
You could use something like
l = ['a','b','c']
d = {element:index for index,element in enumerate(l)}
which will give you each element mapped to its index.
if you want to set some arbitrary value, use
l = ['a','b','c']
d = {element:value for element in l}
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 last year.
Improve this question
EDIT
I have the following dictionary:
dictionary = {'abc': [20, 'john'], 'def': [25, 'jim'], 'ghi': [30, 'jack']}
I would like to sum all of the first values for each key and define it as a variable
Expected answer:
20 + 25 + 30
total_score = 75
You have a dict() having set() assigned to each key. You can not index sets. So considering that the first value in the set will always be the value you want is meaningless.
A workaround is to use list comprehension to build a list() from the set(), that list containing only integer elements. Since you only have one integer per set, then the first index of the list will be the value of interest.
dct = {'abc': {20, 'john'}, 'def': {25, 'jim'}, 'ghi': {30, 'jack'}}
var = 0
for v in dct.values():
v = [x for x in v if isinstance(x, int)][0]
var += v
print(var)
Output:
75
Edit:
Since the OP edited his question, the new code would be:
dct = {'abc': [20, 'john'], 'def': [25, 'jim'], 'ghi': [30, 'jack']}
var = 0
for v in dct.values():
var += v[0]
print(var)
Or:
var = sum(v[0] for v in dct.values())
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 1 year ago.
Improve this question
mydict = {
'name' : ['cat','dog'],
'place' : ['earth','mars'],
'name1' : ['cat','dog'],
'name2' : ['cat','dog'],
'place1' : ['earth','mars'],
'colour' : ['blue','green'],
'colour1' : ['orange']
}
expected_result
[['name','name1','name2'],['place','place1']]
Since 'colour' and 'colour1' are not same we will ignore them.
Probably not the fastest solution, but you can find the duplicate values first, then list the corresponding keys:
>>> values = list(mydict.values())
>>> duplicates = set(tuple(v) for v in values if values.count(v) > 1)
>>> [[k for k, v in mydict.items() if tuple(v) == d] for d in duplicates]
[['name', 'name1', 'name2'], ['place', 'place1']]
from collections import defaultdict
rev = defaultdict(list)
for i in mydict:
rev[tuple(mydict[i])].append(i)
answer = [i for i in rev.values() if len(i)>=2]
#[['name', 'name1', 'name2'], ['place', 'place1']]
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
Python dictionnary:
I need to regroup the keys and add the values accordingly.
For example:
dict = {'A01':6,'A02':5,'A03':2,'B01':2,'B02':3,'B03':2}
new_dict --> {'A':13,'B':7}
You can try this.
>>> dct={'A01':6,'A02':5,'A03':2,'B01':2,'B02':3,'B03':2}
>>> new={}
>>> for k,v in dct.items():
... new[k[0]]=new.get(k[0],0)+v
...
>>> new
{'A': 13, 'B': 7}
Using defaultdict(int)
>>> from collections import defaultdict
>>> new=defaultdict(int)
>>> for k,v in dct.items():
... new[k[0]]+=v
...
>>> new
defaultdict(<class 'int'>, {'A': 13, 'B': 7})
Something like this may work
new_dict = {}
for key, val in dict.items():
new_key = key[0]
if new_key not in new_dict:
new_dict[new_key] = 0
new_dict[new_key] += val
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 4 years ago.
Improve this question
How can I store multiple keys and values in school dictionary?
I was trying to store a list of keys and values in a dictionary with a for loop but I did t know how to go about it.
Can any one help me out?
keys = ['a', 'b']
values = [1, 2]
print(dict(zip(keys,values)))
Output:
{'a':1,'b':2}
You can do following:
keys = ['bob', 'alice']
values = [40, 20]
d = {}
for i in range(len(keys)):
d[keys[i]] = values[i]
Learn the basics of python dictionary and looping. You will find tons of resources in the internet.
For example:
lst1 = ['a', 'b', 'c']
lst2 = [1, 2, 3]
# First way
d1 = {k: v for k, v in zip(lst1, lst2)}
print d1
# {'a': 1, 'c': 3, 'b': 2}
# Second way
d2 = dict(zip(lst1, lst2))
print d2
# {'a': 1, 'c': 3, 'b': 2}