Python Dictionnary: I Need to regroup keys and add their values [closed] - python

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

Related

How to create a dictionary value for each given key? [closed]

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}

How to get all keys where its values are same and data type of values are always list in python? [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 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']]

Turning Key, Value pairs from a Dictionary into strings [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 3 years ago.
Improve this question
I have a dictionary and a string template that I need to fill in with the key, value pairs from the dictionary.
For example, if the dictionary was {'a':'1', 'b':'2'} then I need the string template (key is in value) to read as: "a is in 1" and "b is in 2"
And I need to iterate through the dictionary and apply each key, value pair into the string template.
Here you go. Simply iterate the key, value pairs and format your template.
mydict = {'a':'1', 'b':'2'}
for key, value in mydict.items():
print('{} is in {}'.format(key, value))
Output:
a is in 1
b is in 2
If you would like to get a list of formated strings just do:
mylist = ['{} is in {}'.format(key, value) for key, value in mydict.items()]
mylist will be ['a is in 1', 'b is in 2'].
You can use the following function:
def fill(d, template):
s = ""
for k, v in d.items():
s += f"{k} {template} {v}\n"
return s[:-1]
>>> d = {'a':'1', 'b':'2'}
>>> print(fill(d, 'is in'))
a is in 1
b is in 2
Note that this will only preserve order in python 3.6+.
dictionary = {'a':'1', 'b':'2'}
template = '{} is in {}'
for key, value in dictionary.items():
print(template.format(key, value))
will do the trick
You could be fancy and use itertools.starmap:
from itertools import starmap
d = {'a': '1', 'b': '2'}
list(starmap('{} is in {}'.format, d.items()))
# ['a is in 1', 'b is in 2']
You can also use an f-string for python 3.5+:
d = {'a': '1', 'b': '2'}
print('\n'.join(f'{k} is in {v}' for k, v in d.items()))
a is in 1
b is in 2

Python : Map over multidimensional dictionary using a list [closed]

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

Working with python dictionary [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 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}

Categories