Say I got the following dict :
d = {'x': 1, 'y': 2, 'z': 3}
I want to create a function that appends each key and it's value into a list of tuples, so I coded:
def dict_to_list_of_tuples(dic):
list_of_tuples = []
for key in dic:
list_of_tuples.append((key, dic[key]))
return list_of_tuples
but I get the following output:
[('x', 1), ('y', 2), ('z', 3)]
while I want to get:
[(x, 1), (y, 2), (z, 3)]
Your function is simply list(d.items()):
>>> list(d.items())
[('x', 1), ('y', 2), ('z', 3)]
For printing in the format that you want just make the representation you want with str.format:
>>> "[{}]".format(f", ".join(f"({k}, {v})" for k,v in d.items()) )
'[(x, 1), (y, 2), (z, 3)]'
d = {'x': 1, 'y': 2, 'z': 3}
def dict_to_list_of_tuples(dic):
list_of_tuples = []
for key in dic:
list_of_tuples.append((key, dic[key]))
return list_of_tuples
print(dict_to_list_of_tuples(d))
print("[{}]".format(f", ".join(f"({k}, {v})" for k,v in dict_to_list_of_tuples(d)) ))
Related
I have a list of numbers:
lst = [1, 2, 3, 1,4]
def permutation(lst):
# If lst is empty then there are no permutations
if len(lst) == 0:
return []
# If there is only one element in lst then, only
# one permuatation is possible
if len(lst) == 1:
return [lst]
# Find the permutations for lst if there are
# more than 1 characters
l = [] # empty list that will store current permutation
# Iterate the input(lst) and calculate the permutation
for i in range(len(lst)):
m = lst[i]
# Extract lst[i] or m from the list. remLst is
# remaining list
remLst = lst[:i] + lst[i + 1:]
# Generating all permutations where m is first
# element
for p in permutation(remLst):
l.append([m] + p)
return l
if __name__ == "__main__":
lst = [1, 2, 3, 1,4]
v_out = permutation(lst)
print(v_out)
I am only getting permutations of 4 length, I want permutatins of all lengths, and only distinct permutations. But within each permutation, repetition is allowed.
This should work... Using the permutations function from itertools and making a set out of everything to prevent duplicates from being added to the overall result
In [20]: from itertools import permutations
In [21]: a = [1, 1, 2, 3]
In [22]: all_results = set()
In [23]: for i in range(1, len(a)):
...: all_results.update(set(permutations(a, i)))
...:
In [24]: all_results
Out[24]:
{(1,),
(1, 1),
(1, 1, 2),
(1, 1, 3),
(1, 2),
(1, 2, 1),
(1, 2, 3),
(1, 3),
(1, 3, 1),
(1, 3, 2),
(2,),
(2, 1),
(2, 1, 1),
(2, 1, 3),
(2, 3),
(2, 3, 1),
(3,),
(3, 1),
(3, 1, 1),
(3, 1, 2),
(3, 2),
(3, 2, 1)}
In [25]:
strong textLet's we have a list :
testList1 = [("Sita_English", 1), ("Sita_Maths", 2), ("Ram_English", 3), ("Ram_Maths", 4), ("Shyam_English", 5)]
I have added the values by name:
out2 = list(map(lambda v:(v[0], sum(map(lambda s: s[1], v[1]))), groupby(testList1, key=lambda x: x[0].split('_')[0])))
And i got this as a output:
[('Sita', 3), ('Ram', 7), ('Shyam', 5)]
Now i want to have a Output Like:
[('English', 9), ('Maths', 6)]
Using collections.defaultdict
Ex:
from collections import defaultdict
testList1 = [("Sita_English", 1), ("Sita_Maths", 2), ("Ram_English", 3), ("Ram_Maths", 4), ("Shyam_English", 5)]
out = defaultdict(int)
out2 = defaultdict(int)
for i, v in testList1:
name, lang = i.split("_")
out2[name] += v
out[lang] += v
print(out2) #out2.items() for list of tuples
print(out) #out.items() for list of tuples
Output:
defaultdict(<type 'int'>, {'Sita': 3, 'Ram': 7, 'Shyam': 5})
defaultdict(<type 'int'>, {'Maths': 6, 'English': 9})
As requested by OP
out2 = list(map(lambda v:(v[0], sum(map(lambda s: s[1], v[1]))), groupby(sorted(testList1, key=lambda x: x[0].split("_")[1]), key=lambda x: x[0].split('_')[1])))
#-->[('English', 9), ('Maths', 6)]
Input: 1 2 3 4
Output: (1,2)(3,4)
(1,3)(2,4)
(1,4)(2,3)
I have been able to come up with a solution for the problem but it is efficient. It needs to be optimized.
comb = combinations(Arr,int(n/2))
l = []
for i in comb:
l.append(i)
final_comb = combinations(l,int(n/2))
for i in final_comb:
if is_unique(n,i):
print(i)
def is_unique(n,tup):
k = []
for i in tup:
for j in i:
k.append(j)
if len(set(k)) == n:
return True
return False
The output must be combinations of tuples such that they all have the numbers given as input
Use itertools
from itertools import combinations
list(combinations([1, 2, 3, 4], 2))
>>> [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
I am trying to fix this code:
def word_counter (input_str):
input_str1 = input_str.lower()
word = 0
input_str2 = dict(enumerate(input_str1.split(), start=1))
if word in input_str2:
input_str2[word] += 1
else:
input_str2[word] = 1
return (input_str2)
word_count_dict = word_counter("This is a sentence")
print(sorted(word_count_dict.items()))
so that instead of the output just being:
[(0, 1), (1, 'this'), (2, 'is'), (3, 'a'), (4, 'sentence')]
it will instead return a count of HOW MANY OF EACH word in input_str as so:
[('a', 1), ('is', 1), ('sentence', 1), ('this', 1)]
any help would be appreciated
You can just use collections.Counter:
>>> from collections import Counter
>>> c = Counter('This is a a a sentence'.split())
>>> c
Counter({'a': 3, 'This': 1, 'is': 1, 'sentence': 1})
>>> c['a']
3
>>> c['This']
1
>>> c.items()
[('This', 1), ('a', 3), ('is', 1), ('sentence', 1)]
I have two dictionaries of the following structure:
a) dict1 = {'a':[ [1,2], [3,4] ], 'b':[ [1,2],[5,6] ]}
b) dict2 = {'a':[ [1,2], [5,6] ], 'b':[ [1,2],[7,8] ]}
I need to find the set difference between each key in the dictionary i.e., dict1['a'] - dict2['a'] should return [3,4]. Any thought is appreciated.
The use of mutable items (such as lists) makes the problem MUCH harder, as it precludes the simple use of Python's set data structure. It may be worth making temporary copies/versions which actually use tuples in lieu of those pesky lists:
def tempaux(d):
return dict((k, set(tuple(x) for x in v))
for k, v in d.iteritems())
Now:
def thedifs(dd1, dd2)
d1 = tempaux(dd1)
d2 = tempaux(dd2)
allkeys = set(d1).update(d2)
empty = set()
difs = []
for k in allkeys:
s1 = d1.get(k, empty)
s2 = d2.get(k, empty)
adif = s1 - s2
if adif: difs.append(adif)
return difs
This assumes actual set difference rather than symmetric difference etc. You can of course turn back the tuples into lists before returns, &c, depending on your exact requirements.
>>> s1 = set([(1,2), (3,4)])
>>> s2 = set([(1,2), (5,6)])
>>> s1 - s2
{(3, 4)}
You've got the wrong data structure for what you're trying to do.
Use this instead.
dict1 = {'a': [(1, 2), (3, 4)], 'b': [(1, 2), (5, 6)]}
dict2 = {'a': [(1, 2), (5, 6)], 'b': [(1, 2), (7, 8)]}
Life is simpler when you try to do set operations on immutable objects like tuples.
This will transform your list-of-lists into a list-of-tuples.
>>> dict( (key,[tuple(v) for v in dict1[key]]) for key in dict1 )
{'a': [(1, 2), (3, 4)], 'b': [(1, 2), (5, 6)]}
Here's the complete solution.
>>> dict1t= dict( (key,[tuple(v) for v in dict1[key]]) for key in dict1 )
>>> dict2t= dict( (key,[tuple(v) for v in dict2[key]]) for key in dict2 )
>>> set(dict1t['a'])-set(dict2t['a'])
set([(3, 4)])
applicable to list or dict or number when a and b share the same structure
c={'a':'1','b':'2'}
d={'a':'10','b':'20'}
e={'x':c,'t':15}
f={'x':d,'t':19}
def diff(a,b):
if isinstance(a, int) and isinstance(b, int):
b = b - a
return b
if isinstance(a, str) and isinstance(b, str):
if a.isdigit() and b.isdigit():
b = str(int(b) - int(a))
return b
else:
b = a
return b
if type(a) is list and type(b) is list:
for i in range(len(a)):
b[i] = diff(a[i],b[i])
return b
if type(a) is dict and type(b) is dict:
for k,v in b.iteritems():
b[k] = diff(a[k],b[k])
return b
print diff(e,f)