How to create a dictionary value for each given key? [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 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}

Related

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']]

Python Dictionnary: I Need to regroup keys and add their values [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 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

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}

Merge multiple list of dict with same value in common 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 5 years ago.
Improve this question
I have 4 list of dicts
list1 = [{'a':0,'b':23}, {'a':3,'b':77},{'a':1,'b':99}]
list2 = [{'a':1,'c':666},{'a':4,'c':546}]
list3 = [{'d':33,'a':3},{'d':1111,'a':4},{'d':76,'a':1},{'d':775,'a':0}]
list4 = [{'a':2,'e':12},{'a':4,'e':76}]
Every dict in the list has a common key 'a'. My requirement is 'a' key with same value in dict from all the list should be merged and if a particular key does not exist in the dicts while merging, then assign 0 for those keys or just omit those keys.
for eg. for key 'a' with value 1, from above example we have 2 dicts, one from list1 i.e {'a':0,'b':23} and one is list3, last dict i.e {'d':775,'a':0}, so 1st we have identified the dicts with same 'a' value, now need to merge these dicts
i.e {'a':0, 'b':23, 'c':0, 'd':775, 'e':0}, since both the dict didn't have 'c', 'c' is assigned as 0 here
I should get the output as:
[{'a':0,'b':23,'c':0,'d':775, 'e':0},{'a':1,'b':99,'c':666,'d':76,'e':0},{'a':2,'b':0,'c':0,'d':0,'e':12},{'a':3,'b':77,'c':0,'d':33,'e':0}, {'a':4,'b':0,'c':546,'d':1111,'e':76}]
usings minimum loops or list comprehension
If you want a more pythonic way:
from itertools import groupby
from pprint import pprint
from collections import ChainMap
a = [{'a':0,'b':23}, {'a':3,'b':77}, {'a':1,'b':99}]
b = [{'a':1,'c':666}, {'a':4,'c':546}]
c = [{'d':33,'a':3}, {'d':1111,'a':4}, {'d':76,'a':1}, {'d':775,'a':0}]
d = [{'a':2,'e':12}, {'a':4,'e':76}]
dict_list = a + b + c + d
# You just need to specify the key you want to use in the lambda function
# There's no need to declare the different key values previously
res = map(lambda dict_tuple: dict(ChainMap(*dict_tuple[1])),
groupby(sorted(dict_list,
key=lambda sub_dict: sub_dict["a"]),
key=lambda sub_dict: sub_dict["a"]))
pprint(list(res))
Outputs:
[{'a': 0, 'b': 23, 'd': 775},
{'a': 1, 'b': 99, 'c': 666, 'd': 76},
{'a': 2, 'e': 12},
{'a': 3, 'b': 77, 'd': 33},
{'a': 4, 'c': 546, 'd': 1111, 'e': 76}]
Edit (Improvement):
You can also use
from _operator import itemgetter
key=itemgetter("a")
instead of
key=lambda sub_dict: sub_dict["a"]
The version with itemgetter is much faster. Using the example you provided:
- Lambda: 0.037109375ms
- Itemgetter: 0.009033203125ms

Categories