This question already has answers here:
Inverting a dictionary with list values
(6 answers)
Closed 2 years ago.
I am trying to find all the keys that include the corresponding values using the following code,
I have the current output and expected output,can someone provide guidance on what I am doing wrong?
CODE:-
info = [
{'x':['y','z']},
{'a':['y','x']},
{'p':['q','z']},
{'z':['x','q']}
]
output_list = []
for d in info:
for key,value in d.items():
print (key,value)
new_list,new_dict = [],{}
for element in value:
print (element)
new_list.append(key)
new_dict[key] = new_dict
output_list.append(new_list)
print (output_list)
CURRENT OUTPUT:-
[['x', 'x'], ['x', 'x'], ['a', 'a'], ['a', 'a'], ['p', 'p'], ['p', 'p'], ['z', 'z'], ['z', 'z']]
EXPECTED OUTPUT:
[
{'y':['x','a']},
{'z' = ['x','p']},
{'x' = ['a','z']},
{'q' = ['p','z']}
]
Try this:
inverse_dict = {}
for d in info:
for k, v in d.items():
for a in v:
inverse_dict.setdefault(a, []).append(k)
inverse_dict = [{k: v} for k, v in inverse_dict.items()]
[{'y': ['x', 'a']}, {'z': ['x', 'p']}, {'x': ['a', 'z']}, {'q': ['p', 'z']}]
You can create a dictionary whose keys are all the set of all the values of dictionaries in info and then make a list of dictionaries (one for each key) out of them.
Related
I have a dictionary of lists:
g = {'a': ['b', 'c'], 'b': ['a', 'd', 'e']}
in which some of the values are not present as keys. I want to add all values, as keys with empty lists, which are not present in keys. Current I am attempting to do this as follows:
for keys, values in g.items():
for value in values:
if value not in keys:
g[value] = []
Running the above code gives a traceback: RuntimeError: dictionary changed size during iteration. I checked other related questions in Stackoverflow but couldn't find a related task.
I look to have the following output:
{'a': ['b', 'c'], 'b': ['a', 'd', 'e'], 'c': [], 'd': [], 'e': []}
Solution
g = {'a': ['b', 'c'], 'b': ['a', 'd', 'e']}
for keys, values in list(g.items()):
for value in values:
if value not in g:
g[value] = []
print(g)
Explanation
Please refer to this Stack Overflow post for more information regarding using list(). Also, your conditional should check if value is in g, not in keys.
This question already has answers here:
Get key by value in dictionary
(43 answers)
Closed 2 years ago.
How to print the key of the dictionary with the value matches to the value provided
dict1 = {'A': ['1', '2'],'B': ['3', '4']}
val = ['1', '2']
for k, v in dict1.items():
if v == val:
print(k)
expected output : 'A'
The error in your code is that you did not add the ending ' for the string when you set the key 'B', and running through the rest of your code, it seems fine. For reference:
dict1 = {'A': ['1', '2'],'B': ['3', '4']}
val = ['1', '2']
for k, v in dict1.items():
if v == val:
print(k)
I'm trying to make a script that searches for emails inside a list. The problem is when adding the email found to the email list it returns the email string but it is chopped like in .split()
my_list = ['jose', 'ana', 'ana#gmail.com']
email_list = []
for i in my_list:
if '#gmail.com' in i:
print(i)
email_list += i
print(email_list)
the first print() statement returns what I expected 'ana#gmail.com', but when I print the email_list I get it all chopped, output:
ana#gmail.com
['a', 'n', 'a', '#', 'g', 'm', 'a', 'i', 'l', '.', 'c', 'o', 'm']
You can't add to a list like that. You'll want to use email_list.append(i)
Python does this because you can do mathematical operations on list and do fun things, e.g.
l = []
l = 5 * [2]
l
[2, 2, 2, 2, 2]
I have following two lists:
list1 = ['17-Q2', '1.00', '17-Q3', '2.00', '17-Q4', '5.00', '18-Q1', '6.00']
list2 = ['17-Q2', '1', '17-Q3', '2', '17-Q4', '5', '18-Q1', '6']
I want a dictionary in the following way. Can I do that in Python?
result = [17-Q2: 1(1.00), 17-Q3: 2(2.00), 17-Q4: 5(5.00), 18-Q1: 6(6.00)]
Here's one approach to this:
result = {}
list1=['17-Q2', '1.00', '17-Q3', '2.00', '17-Q4', '5.00', '18-Q1', '6.00']
list2=['17-Q2', '1', '17-Q3', '2', '17-Q4', '5', '18-Q1', '6']
for i in range(0, len(list1)-1, 2):
result[list1[i]] = list2[i + 1] + '(' + list1[i+1] + ')' ;
You can zip the two lists and then zip the resulting iterable with itself so that you can iterate through it in pairs to construct the desired dict:
i = zip(list1, list2)
result = {k: '%s(%s)' % (v2, v1) for (k, _), (v1, v2) in zip(i, i)}
result becomes:
{'17-Q2': '1(1.00)', '17-Q3': '2(2.00)', '17-Q4': '5(5.00)', '18-Q1': '6(6.00)'}
You can use zip and dict.
keys = ["a", "b", "c", "d"]
values = ["A", "B", "C"]
print(dict(zip(keys, values)))
# prints: {'a': 'A', 'b': 'B', 'c': 'C'}
This works because dict can take a list (or any iterator) of tuples of (key, value) to be created. The zip function allows to build tuples from lists:
zip returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.
Notice that this will only return a dictionary that pairs the shortest list (either keys or value) with the corresponding element.
If you wish to have a default value for unpaired elements you can always use itertools.zip_longest
from itertools import zip_longest
keys = ["a", "b", "c", "d"]
values = ["A", "B", "C"]
print(dict(zip_longest(keys, values)))
# prints: {'a': 'A', 'b': 'B', 'c': 'C', 'd': None}
You can also use zip_longest keyword parameter fillvalue to have something else than None when the corresponding value isn't found.
On the other hand, if you have more values than keys, this wouldn't make much sense as you would erase the default key (namely fillvalue) for every missing element.
Assuming your input to be as follows:
list1 = ['17-Q2', '1.00', '17-Q3', '2.00', '17-Q4', '5.00', '18-Q1', '6.00']
list2 = ['17-Q2', '1', '17-Q3', '2', '17-Q4', '5', '18-Q1', '6']
And Desired Output to be as follows:
result = {17-Q2: 1(1.00), 17-Q3: 2(2.00), 17-Q4: 5(5.00), 18-Q1: 6(6.00)}
Following code with a single while loop could help:
from collections import OrderedDict
final_dict = dict()
i = 0 # Initializing the counter
while (i<len(list1)):
# Updating the final dict
final_dict.update({list1[i]:str(list2[i+1]) + "(" + str(list1[i+1]) + ")"})
i += 2 # Incrementing by two in order to land on the alternative index
# If u want sorted dictionary
sorted_dict = OrderedDict(sorted(final_dict.items()))
print (sorted_dict)
I need to do this:
from collections import deque
def list3_to2(list1, list2, list3):
Left = []
Right = []
q = deque()
for a, b, c in list1, list2, list3:
q.append(a)
q.append(b)
q.append(c)
tmp = 1
while q:
if tmp % 2 == 0:
Left.append(q.popleft())
else:
Right.append(q.popleft())
tmp += 1
return Left, Right
a = ['a', 'b', 'c']
b = ['d', 'e', 'f']
c = ['g', 'h', 'i']
l, r = list3_to2(a, b, c)
print(l)
print(r)
But instead of two lists in result i got four lists.
Output:
['b', 'd', 'f', 'h']
['a', 'c', 'e', 'g', 'i']
['b', 'd', 'f', 'h']
['a', 'c', 'e', 'g', 'i']
What i'm doing wrong?
Basically i need to transform 3 lists into 2 lists using deque with correct order.
Thank to everyone. I got it. My function just returning a tuple. That's why i got both lists in varibles l and r. Just need to type l = list3_to2(a, b, c)[0] and r = list3_to2(a, b, c)[1]