Quick inquiry about dict mapping - python

How can I map single or multiple things to a single element in a dictionary in python.
For example:
dict of str: {str: [str, int]}

myDict = dict()
myDict["myString"] = ["myList", 1, 0.0]
print myDict
Output
{'myString': ['myList', 1, 0.0]}
Example from http://docs.python.org/2/library/stdtypes.html#mapping-types-dict
You can create dict in python in the following ways
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True
You can use a list instead of any of the values (1, 2 or 3)

Related

Python3 Determine if two dictionaries are equal [duplicate]

This question already has answers here:
Comparing two dictionaries and checking how many (key, value) pairs are equal
(28 answers)
Closed 4 years ago.
This seems trivial, but I cannot find a built-in or simple way to determine if two dictionaries are equal.
What I want is:
a = {'foo': 1, 'bar': 2}
b = {'foo': 1, 'bar': 2}
c = {'bar': 2, 'foo': 1}
d = {'foo': 2, 'bar': 1}
e = {'foo': 1, 'bar': 2, 'baz':3}
f = {'foo': 1}
equal(a, b) # True
equal(a, c) # True - order does not matter
equal(a, d) # False - values do not match
equal(a, e) # False - e has additional elements
equal(a, f) # False - a has additional elements
I could make a short looping script, but I cannot imagine that mine is such a unique use case.
== works
a = dict(one=1, two=2, three=3)
b = {'one': 1, 'two': 2, 'three': 3}
c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
d = dict([('two', 2), ('one', 1), ('three', 3)])
e = dict({'three': 3, 'one': 1, 'two': 2})
a == b == c == d == e
True
I hope the above example helps you.
The good old == statement works.

Python: summarizing data from list using index from another list

I have two lists:
L1 = ['A','B','A','C','A']
L2 = [1, 4, 6, 1, 3]
I want to create a dictionary which has the following output:
DictOutSum = {'A':10, 'B':4, 'C':1}
DictOutCount = {'A':3, 'B':1, 'C':1}
i.e. Lists L1 and L2 both have same number of elements and the elements in them corresponds one to one. I want to find sum of all numbers in L2 for each unique element in L1 and make a dictionary out of it(DictOutSum). I also want to create another dictionary which stores the counts of number of unique elements of L1(DictOutCount).
I don't even have an idea where to start for this other than to use a for loop.
Pure python implementation:
>>> dict_sum = dict.fromkeys(L1, 0)
>>> dict_count = dict.fromkeys(L1, 0)
>>> for k,n in zip(L1, L2):
... dict_sum[k] += n
... dict_count[k] += 1
...
>>> dict_sum
{'A': 10, 'B': 4, 'C': 1}
>>> dict_count
{'A': 3, 'B': 1, 'C': 1}
Fancy one-liner implementations:
>>> from collections import Counter
>>> Counter(L1) # dict_count
Counter({'A': 3, 'B': 1, 'C': 1})
>>> sum((Counter({k:v}) for k,v in zip(L1, L2)), Counter()) # dict_sum
Counter({'A': 10, 'B': 4, 'C': 1})
You should use the zip builtin function
import collections
DictOutSum = collections.defaultdict(int)
DictOutCount = collections.defaultdict(int)
for l1, l2 in zip(L1, L2):
DictOutSum[l1] += l2
DictOutCount[l1] += 1
>>> L1 = ['A','B','A','C','A']
>>> L2 = [1, 4, 6, 1, 3]
>>>
>>> DictOutCount = {v:0 for v in L1}
>>> DictOutSum = {v:0 for v in L1}
>>> for v1,v2 in zip(L1,L2):
... DictOutCount[v1] += 1
... DictOutSum[v1] += v2
...
>>>
>>> DictOutCount
{'A': 3, 'C': 1, 'B': 1}
>>> DictOutSum
{'A': 10, 'C': 1, 'B': 4}
>>>
The mega elementary way
L1 = ['A','B','A','C','A']
L2 = [1, 4, 6, 1, 3]
# Carries the information
myDict = {}
# Build the dictionary
for x in range(0,len(L1)):
# Initialize the dictionary IF the key doesn't exist
if L1[x] not in myDict:
myDict[L1[x]] = {}
myDict[L1[x]]['sum'] = 0
myDict[L1[x]]['count'] = 0
# Collect the information you need
myDict[L1[x]][x] = L2[x]
myDict[L1[x]]['sum'] += L2[x]
myDict[L1[x]]['count'] += 1
# Build the other two dictionaries
DictOutSum = {}
DictOutCount = {}
# Literally feed the data
for element in myDict:
DictOutSum[element] = myDict[element]['sum']
DictOutCount[element] = myDict[element]['count']
print DictOutSum
# {'A': 10, 'C': 1, 'B': 4}
print DictOutCount
# {'A': 3, 'C': 1, 'B': 1}
Side note: From your username, are you Persian?
DictOutCount, use collections.Counter,
import collections
DictOutCount = collections.Counter(L1)
print(DictOutCount)
Counter({'A': 3, 'C': 1, 'B': 1})
DictOutSum,
DictOutSum = dict()
for k, v in zip(L1, L2):
DictOutSum[k] = DictOutSum.get(k, 0) + v
print(DictOutSum)
# Output
{'A': 10, 'C': 1, 'B': 4}
Previous answer, DictOutSum,
import itertools
import operator
import functools
DictOutSum = dict()
for name, group in itertools.groupby(sorted(itertools.izip(L1, L2)), operator.itemgetter(0)):
DictOutSum[name] = functools.reduce(operator.add, map(operator.itemgetter(1), group))
print(DictOutSum)
{'A': 10, 'C': 1, 'B': 4}
The main steps are:
use itertools.izip to make an iterator that aggregates elements from each of L1 and L2
use itertools.groupby to make an iterator that returns consecutive keys and groups from the iterable (sorting before that)
use functools.reduce for cumulatively addition

Counting all the differences in 2 dictionaries and displaying them all

Suppose I have 2 dictionaries:
A = {'banana':10, 'apple':2, 'pear':5, 'orange':3}
B = {'banana':7, 'orange':5, 'strawberry':4, 'blueberry':1, 'kiwi':10}
Now, I need to print all the difference of these dictionaries and display them all (even if there is a key in A that is not in B or otherwise) and of course in absolute values, so the result should be:
c = {'banana':3, 'apple':2, 'pear':5, 'orange':2, 'strawberry':4, 'blueberry':1, 'kiwi':10}
Any ideas? I've seen some posts before but only partial answers to this need.
Using collections.Counter:
from collections import Counter
A = {'banana':10, 'apple':2, 'pear':5, 'orange':3}
B = {'banana':7, 'orange':5, 'strawberry':4, 'blueberry':1, 'kiwi':10}
A_Counter, B_Counter = Counter(A), Counter(B)
print((A_Counter - B_Counter) | (B_Counter - A_Counter))
Output:
Counter({'kiwi': 10, 'pear': 5, 'strawberry': 4, 'banana': 3, 'apple': 2, 'orange': 2, 'blueberry': 1})
In py2x A.viewkeys() | B.viewkeys() will return the union of keys from both A & B, and then you can use a dict comprehension to get the desired result.
In [14]: A = {'banana':10, 'apple':2, 'pear':5, 'orange':3}
In [15]: B = {'banana':7, 'orange':5, 'strawberry':4, 'blueberry':1, 'kiwi':10}
In [16]: {x : abs( A.get(x,0) - B.get(x,0) ) for x in A.viewkeys() | B.viewkeys()}
Out[16]:
{'apple': 2,
'banana': 3,
'blueberry': 1,
'kiwi': 10,
'orange': 2,
'pear': 5,
'strawberry': 4}
For py3x use : A.keys() | B.keys()
For both py2x and py3x: set(A).union(B)

Python Joining two dictionnary with similar content

I am looking for a Pythonic way (the less code possible) to unite the content of two dictionnaries :
basket1 = {"ham":2,"eggs":3}
basket2 = {"eggs":4,"spam":1}
I want to get a third basket that is going to be the "sum" of the two other, basket 3 should be:
basket3 --> {"ham":2,"eggs":7,"spam":1}
If possible, doing this using set
I'd use a Counter, which is a kind of defaultdict with some nice properties:
>>> from collections import Counter
>>> basket1 = {"ham":2,"eggs":3}
>>> basket2 = {"eggs":4,"spam":1}
>>> basket_sum = Counter(basket1) + Counter(basket2)
>>> basket_sum
Counter({'eggs': 7, 'ham': 2, 'spam': 1})
which you could convert back into a pure dict if you wanted:
>>> dict(basket_sum)
{'eggs': 7, 'ham': 2, 'spam': 1}
Since you're trying to count the values, use collections.Counter:
basket3 = collections.Counter(basket1)
basket3.update(basket2)
Or:
basket3 = collections.Counter(basket1) + collections.Counter(basket2)
In [2]: basket1 = {"ham":2,"eggs":3}
In [3]: basket2 = {"eggs":4,"spam":1}
In [4]: baskets = [basket1, basket2]
In [5]: answer = collections.defaultdict(int)
In [6]: for basket in baskets:
...: for item in basket:
...: answer[item] += basket[item]
...:
In [7]: answer
Out[7]: defaultdict(<type 'int'>, {'eggs': 7, 'ham': 2, 'spam': 1})
In [8]: dict(answer)
Out[8]: {'eggs': 7, 'ham': 2, 'spam': 1}

List of tuples to dictionary [duplicate]

This question already has answers here:
How to convert list of key-value tuples into dictionary?
(7 answers)
Closed 2 years ago.
Here's how I'm currently converting a list of tuples to dictionary in Python:
l = [('a',1),('b',2)]
h = {}
[h.update({k:v}) for k,v in l]
> [None, None]
h
> {'a': 1, 'b': 2}
Is there a better way? It seems like there should be a one-liner to do this.
Just call dict() on the list of tuples directly
>>> my_list = [('a', 1), ('b', 2)]
>>> dict(my_list)
{'a': 1, 'b': 2}
It seems everyone here assumes the list of tuples have one to one mapping between key and values (e.g. it does not have duplicated keys for the dictionary). As this is the first question coming up searching on this topic, I post an answer for a more general case where we have to deal with duplicates:
mylist = [(a,1),(a,2),(b,3)]
result = {}
for i in mylist:
result.setdefault(i[0],[]).append(i[1])
print(result)
>>> result = {a:[1,2], b:[3]}
The dict constructor accepts input exactly as you have it (key/value tuples).
>>> l = [('a',1),('b',2)]
>>> d = dict(l)
>>> d
{'a': 1, 'b': 2}
From the documentation:
For example, these all return a
dictionary equal to {"one": 1, "two":
2}:
dict(one=1, two=2)
dict({'one': 1, 'two': 2})
dict(zip(('one', 'two'), (1, 2)))
dict([['two', 2], ['one', 1]])
With dict comprehension:
h = {k:v for k,v in l}
Functional decision for #pegah answer:
from itertools import groupby
mylist = [('a', 1), ('b', 3), ('a', 2), ('b', 4)]
#mylist = iter([('a', 1), ('b', 3), ('a', 2), ('b', 4)])
result = { k : [*map(lambda v: v[1], values)]
for k, values in groupby(sorted(mylist, key=lambda x: x[0]), lambda x: x[0])
}
print(result)
# {'a': [1, 2], 'b': [3, 4]}

Categories