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)
Related
I have the following list of dicts:
lst = [{'a':1, 'b':2, 'c':3}, {'a':1, 'b':2, 'd':3}, {'a':1, 'c':2, 'k':3}, {'d':1, 'k':2, 'l':3}]
I want to filter the list of dicts (in my case it's a list of thousands or even more dicts, with different keys with some overlap) to be a list containing all the dicts that have keys: ["a", "b"]. I want to filter each dict only to these a and b keys, and if they don't exist, don't include the dictionary in the final list. I am using:
[{"a": d.get("a"), "b": d.get("b")} for d in lst]
Please advise for an elegant way to solve it.
The dictionary keys-view is set-like, so it supports subset comparisons by using <= operator:
>>> keys = set("ab")
>>> [{k: d[k] for k in keys} for d in lst if keys <= d.keys()]
[{'a': 1, 'b': 2}, {'a': 1, 'b': 2}]
I have figured it out and here is my alternative:
lst = [{'a':1, 'b':2, 'c':3}, {'a':1, 'b':2, 'd':3}, {'a':1, 'c':2, 'k':3}, {'d':1, 'k':2, 'l':3}]
keys = set("ab")
[i for i in [{k: d.get(k) for k in keys if k in d} for d in lst] if i]
Gives the desired answer:
[{'b': 2, 'a': 1}, {'b': 2, 'a': 1}, {'a': 1}]
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.
Im trying to do this: if an element of list1 is in list2, that element would have to be replaced with a random element.
It would some something like this:
replace(["a","b","c"],"x",["c","n","a","b","l"])
And i would have to return this:
["x","n","x","x","l"]
You can use list-comprehension for that.
For example:
def replace(lst1, elem, lst2):
s = set(lst1)
return [elem if v in s else v for v in lst2]
out = replace(["a", "b", "c"], "x", ["c", "n", "a", "b", "l"])
print(out)
Prints:
['x', 'n', 'x', 'x', 'l']
I want to replace two or more elements with a single element in a list like this:
mylist=['a','b','c']
Now I want to replace 'a' and 'b' elements with another element 'z'.
So output should be:
['z','z','c']
a list-comprehension an option:
mylist = ['a', 'b', 'c']
new_list = [x if x not in "ab" else "z" for x in mylist]
print(new_list) # ['z', 'z', 'c']
if the elements you want to replace are more complicated you could try:
if x not in {"a", "b"}
if you want to change things based on the index i you can use enumerate:
new_list = [x if i >= 2 else "z" for i, x in enumerate(mylist)]
print(new_list) # ['z', 'z', 'c']
but then you could consider slicing:
new_list = 2 * ["z"] + mylist[2:]
I have this Python Code:
def dictofvalues():
values = {'A': '1', 'C': '3', 'B': '2'}
return(values)
def main():
values = dictofvalues()
print(sorted(values))
Which prints: A, B, C.
However, I want it to print A:1, B:2, C:3.
In other words, I want it to print the item with the assigned value as well.
How does one go about doing this?
Simply print out the dictionary as a list of tuples:
def dictofvalues():
values = {'A': '1', 'C': '3', 'B': '2'}
return(values)
def main():
values = dictofvalues().items()
print(sorted(values))
You can use OrderedDict from module collections:
from collections import OrderedDict
def dictofvalues():
values = {'A': '1', 'C': '3', 'B': '2'}
return(values)
def main():
values = dictofvalues()
print(OrderedDict(sorted(d.items())))
I hope it helps,