I have a dictionary like this:
a= {1982: [(1,2,3,4)],
1542: [(4,5,6,7),
(4,6,5,7)]}
and I want to change the all the tuples (1,2,3,4),(4,5,6,7),(4,6,5,7) to lists, in this case: [1,2,3,4], [4,5,6,7], [4,6,5,7]
I have tried
for key, value in a.items():
for i in value:
i = tuple(i)
but it does now work. How can I achieve it?
As far as I understand you want to convert each tuple in a list. You can do this using a dictionary comprehension:
{k: [list(ti) for ti in v] for k, v in a.items()}
will give
{1542: [[4, 5, 6, 7], [4, 6, 5, 7]], 1982: [[1, 2, 3, 4]]}
Is that what you are after?
In-place:
for key, value in a.items():
for i, t in enumerate(value):
value[i]= list(t)
New objects:
{key: [list(t) for t in value] for key, value in a.items()}
You can use "tupleo" library
from tupleo import tupleo.
val = tupleo.tupleToList(a[1542]).
print(val)
[[4,5,6,7], [4,6,5,7]]
tupleo gives you full depth level conversion of tuple to list.
and it have functionality to convert tuple to dict also based on index.
Related
If I have a dictionary with each key having a list of values for example:
my_dict={'key1':[1, 6, 7, -9], 'key2':[2, 5, 10, -5,], 'key3':[-8, 1, -2, 6]}
And I want to create a loop statement to go through each value within the lists and change the value within my dictionary to 0 for each negative value. I can create a loop statement to go through each value and check if the value is negative but I can't figure out how to amend the dictionary directly:
for keys, values in my_dict.items():
for value in values:
if value < 0:
value=0
How to I alter that last line (or do I have to change more lines) to be able to amend my dictionary directly to replace the negative values with 0?
Thanks in advance
One approach is to iterate over the .items of the dictionary and override each value directly using enumerate to keep track of the indices:
my_dict={'key1':[1, 6, 7, -9], 'key2':[2, 5, 10, -5,], 'key3':[-8, 1, -2, 6]}
for key, value in my_dict.items():
for i, val in enumerate(value):
value[i] = 0 if val < 0 else val
print(my_dict)
Output
{'key1': [1, 6, 7, 0], 'key2': [2, 5, 10, 0], 'key3': [0, 1, 0, 6]}
Alternative using the slicing operator and a list comprehension:
for key, value in my_dict.items():
value[:] = [0 if val < 0 else val for val in value]
Some other useful resources:
Looping Techniques, discusses pythonic approaches to looping
Python names and values for understanding how variables work in Python
Slice assignment some light on how the second approach works
Using max in a nested comprehension:
my_dict = {k: [max(0, v) for v in vals] for k, vals in my_dict.items()}
I am playing around with dictionaries, and thought how would I create a dictionary using comprehensions. I thought
{k:v for k in [0,1,2] for v in [5,8,7]}
would print as
{0:5, 1:8, 2:7}
But instead it prints as
{0: 7, 1: 7, 2: 7}
Why is this happening and what modifications would I need to make to get the first output?
Your list comprehension is equivalent to nested loops:
result = {}
for v in [5, 8, 7]:
for k in [0, 1, 2]:
result[k] = v
So each iteration of the outer loop sets all the keys to that value, and at the end you have the last value in all of them.
Use zip() to iterate over two lists in parallel.
{k: v for k, v in zip([0, 1, 2], [5, 8, 7])}
You can also just use the dict() constructor:
dict(zip([0, 1, 2], [5, 8, 7]))
Whenever you have trouble with a comprehension, unroll it into the equivalent loops. Which in this case goes:
mydict = {}
for v in [5,8,7]:
for k in [0,1,2]:
mydict[k] = v
Each successive assignment to mydict[k] overwrites the previous one.
I have two lists, lst and my_dict. lst is storing IDs and lst_of_dict is a dictionaries with keys and values of ID.
Here I want to extract keys from lst_of_dict and add them into a new list if the corresponding values are matched with the ID of lst.
Here is the examples:
lst = [1, 2, 5]
my_dict = {'44': 2, '801': 1, '7': 5}
given these lists, I want to create a new list like below:
new_lst = [801, 44, 7]
How do you accomplish this? Thank you in advance.
[EDIT]
I'm really sorry but type of lst_of_dict is a dict, I was wrong.
You can iterate over the list of dictionaries and use index to replace the values in a copy of the original list (or just the original list if you don't want to preserve it)
lst = [1, 2, 5]
my_dict = {'44': 2, '801': 1, '7': 5}
new_lst = lst[:]
for k, v in my_dict.items():
new_lst[new_lst.index(v)] = int(k)
print(new_lst) # [801, 44, 7]
Edit:
If there might be a mismatch between the values in the list and the dictionary you can initialize the new list with Nones and filter them afterwards
new_lst = [None] * len(lst)
for k, v in my_dict.items():
if v in lst:
new_lst[lst.index(v)] = int(k)
new_lst = list(filter(lambda x: x, new_lst))
Here is a way you can do it:
lst = [1, 2, 5]
lst_of_dict = [
{'44': 2},
{'801': 1},
{'7': 5}
]
invert = {i:int(k)for v in lst_of_dict for k,i in v.items()}
print([invert.get(x) for x in invert])
#== Output [44, 801, 7]
I have a program that stores data in a list. The current and desired output is in the format:
# Current Input
[{'Devices': ['laptops', 'tablets'],
'ParentCategory': ['computers', 'computers']},
{'Devices': ['touch'], 'ParentCategory': ['phones']}]
# Desired Output
[{'Devices': ['laptops', 'tablets','touch'],
'ParentCategory': ['computers', 'computers','phones']}]
Can you give me an idea on how to combine the lists with another python line of code or logic to get the desired output?
You can do something like this:
def convert(a):
d = {}
for x in a:
for key,val in x.items():
if key not in d:
d[key] = []
d[key] += val
return d
Code above is for Python 3.
If you're on Python 2.7, then I believe that you should replace items with iteritems.
Solution using a dict comprehension: build the merged dictionary first by figuring out which keys it should have, then by concatenating all the lists for each key. The set of keys, and each resulting list, are built using itertools.chain.from_iterable.
from itertools import chain
def merge_dicts(*dicts):
return {
k: list(chain.from_iterable( d[k] for d in dicts if k in d ))
for k in set(chain.from_iterable(dicts))
}
Usage:
>>> merge_dicts({'a': [1, 2, 3], 'b': [4, 5]}, {'a': [6, 7], 'c': [8]})
{'a': [1, 2, 3, 6, 7], 'b': [4, 5], 'c': [8]}
>>> ds = [
{'Devices': ['laptops', 'tablets'],
'ParentCategory': ['computers', 'computers']},
{'Devices': ['touch'],
'ParentCategory': ['phones']}
]
>>> merge_dicts(*ds)
{'ParentCategory': ['computers', 'computers', 'phones'],
'Devices': ['laptops', 'tablets', 'touch']}
If I have a dictionary such as:
my_dict = {"A": [1, 2, 3], "B": [9, -4, 2], "C": [3, 99, 1]}
How do I create a new dictionary with sums of the values for each key?
result = {"A": 6, "B": 7, "C": 103}
Use sum() function:
my_dict = {"A": [1, 2, 3], "B": [9, -4, 2], "C": [3, 99, 1]}
result = {}
for k, v in my_dict.items():
result[k] = sum(v)
print(result)
Or just create a dict with a dictionary comprehension:
result = {k: sum(v) for k, v in my_dict.items()}
Output:
{'A': 6, 'B': 7, 'C': 103}
Try This:
def sumDictionaryValues(d):
new_d = {}
for i in d:
new_d[i]= sum(d[i])
return new_d
Just a for loop:
new = {}
for key in dict:
new_d[key]= sum(d[key])
new the dictionary having all the summed values
One liners- for the same, just demonstrating some ways to get the expected result,in python3
my_dict = {"A": [1, 2, 3], "B": [9, -4, 2], "C": [3, 99, 1]}
Using my_dict.keys():- That returns a list containing the my_dict's keys, with dictionary comprehension.
res_dict = {key : sum(my_dict[key]) for key in my_dict.keys()}
Note that my_dict.keys() produce a list of keys in the dictionary,
But python dictionary data structure also got an iterator implementation to loop
through keys, (which is faster, but not recommended always) so, this
will also give same result,
res_dict = {key : sum(my_dict[key]) for key in my_dict}
Using my_dict.items():- That returns a list containing a tuple for each key
value pair of dictionary, by unpacking them gives a best single line solution for this,
res_dict = {key : sum(val) for key, val in my_dict.items()}
Using my_dict.values():- That returns a list of all the values in the
dictionary(here the list of each lists),
note:- This one is not intended as a direct solution, just for demonstrating the three python methods used to traverse through a dictionary
res_dict = dict(zip(my_dict.keys(), [sum(val) for val in my_dict.values()]))
The zip function accepts iterators(lists, tuples, strings..), and pairs similar indexed items together and returns a zip object, by using dict it is converted back to a dictionary.