Working with python dictionary [closed] - python

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}

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}

Sum the nth value for every key in a python dictionary [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 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())

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

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