Deleting an item in a dictionary using dictionary comprehension [duplicate] - python

This question already has an answer here:
python delete dict keys in list comprehension
(1 answer)
Closed 2 years ago.
How can I delet an item from a dictionary if the value of an item is a specific string, using dictionay comprehension?

You need to keep the other ones
values = {'a': '1', 'b': '2', 'c': '4', 'd': '4'}
toRemove = '4'
values = {k: v for k, v in values.items() if v != toRemove}
print(values) # {'a': '1', 'b': '2'}

Related

Why does this return a list of characters instead of a string in Python when iterating a dictionary using items() [duplicate]

This question already has an answer here:
Is a Python list's += operator equivalent to append() or extend()? [duplicate]
(1 answer)
Closed 6 months ago.
Python question:
Why does this return a list of characters instead of a list of the keys as strings?
d = {'key1': 'aaa', 'key2': 'aaa', 'key3': 'bbb'}
a=[]
for k,v in d.items():
a += k
print(a)
I received the following result:
['k', 'e', 'y', '1', 'k', 'e', 'y', '2', 'k', 'e', 'y', '3']
Because the += operator in lists expects an iterable, resulting in a concatenation of that iterable into the list. A string is an iterable of its chars.
To have the results you expect, do either:
a.append(k)
or
a += [k]
Use append() to append k to a list:
d = {'key1': 'aaa', 'key2': 'aaa', 'key3': 'bbb'}
a=[]
for k,v in d.items():
a.append(k)
print(a)

Python: Turn Nested List to Dictionary [duplicate]

This question already has answers here:
Get first element of sublist as dictionary key in python
(5 answers)
Closed 3 years ago.
I am trying to turn a nested list like this:
(Example list)
[['A','1','2','3'], ['B','4','5','6'],...]
To a dictionary that looks like this
{'A':'1','2','3','B': '4','5','6'}
Can someone please help me?
You can use dictionary comprehension:
lst = [['A','1','2','3'], ['B','4','5','6']]
{e[0]: e[1:] for e in lst}
This returns:
{'A': ['1', '2', '3'], 'B': ['4', '5', '6']}

Convert list to dictionary with duplicate keys using dict comprehension [duplicate]

This question already has answers here:
How can one make a dictionary with duplicate keys in Python?
(9 answers)
Closed 6 months ago.
Good day all,
I am trying to convert a list of length-2 items to a dictionary using the below:
my_list = ["b4", "c3", "c5"]
my_dict = {key: value for (key, value) in my_list}
The issue is that when a key occurrence is more than one in the list, only the last key and its value are kept.
So in this case instead of
my_dict = {'c': '3', 'c': '5', 'b': '4'}
I get
my_dict = {'c': '5', 'b': '4'}
How can I keep all key:value pairs even if there are duplicate keys.
Thanks
For one key in a dictionary you can only store one value.
You can chose to have the value as a list.
{'b': ['4'], 'c': ['3', '5']}
following code will do that for you :
new_dict = {}
for (key, value) in my_list:
if key in new_dict:
new_dict[key].append(value)
else:
new_dict[key] = [value]
print(new_dict)
# output: {'b': ['4'], 'c': ['3', '5']}
Same thing can be done with setdefault. Thanks #Aadit M Shah for pointing it out
new_dict = {}
for (key, value) in my_list:
new_dict.setdefault(key, []).append(value)
print(new_dict)
# output: {'b': ['4'], 'c': ['3', '5']}
Same thing can be done with defaultdict. Thanks #MMF for pointing it out.
from collections import defaultdict
new_dict = defaultdict(list)
for (key, value) in my_list:
new_dict[key].append(value)
print(new_dict)
# output: defaultdict(<class 'list'>, {'b': ['4'], 'c': ['3', '5']})
you can also chose to store the value as a list of dictionaries:
[{'b': '4'}, {'c': '3'}, {'c': '5'}]
following code will do that for you
new_list = [{key: value} for (key, value) in my_list]
If you don't care about the O(n^2) asymptotic behaviour you can use a dict comprehension including a list comprehension:
>>> {key: [i[1] for i in my_list if i[0] == key] for (key, value) in my_list}
{'b': ['4'], 'c': ['3', '5']}
or the iteration_utilities.groupedby function (which might be even faster than using collections.defaultdict):
>>> from iteration_utilities import groupedby
>>> from operator import itemgetter
>>> groupedby(my_list, key=itemgetter(0), keep=itemgetter(1))
{'b': ['4'], 'c': ['3', '5']}
You can use defaultdict to avoid checking if a key is in the dictionnary or not :
from collections import defaultdict
my_dict = defaultdict(list)
for k, v in my_list:
my_dict[k].append(v)
Output :
defaultdict(list, {'b': ['4'], 'c': ['3', '5']})

why does this output returns different value every time? [duplicate]

This question already has answers here:
Why is the order in dictionaries and sets arbitrary?
(5 answers)
Closed 6 years ago.
def solution(dict, output, ini):
if (dict == None):
return None
else:
for key in dict:
if str(type(dict[key])) != str(type({})):
print(key)
output[ini + key] = dict[key]
else:
return solution(dict[key], output, ini + key + '.')
return output
a = {
'Key1': '1',
'Key2': {
'a': '2',
'b': '3',
'c': {
'd': '3',
'e': '1'
}
}
}
print(solution(a, {}, ""))
Hello I am trying to make a function that flattens nested dictionary.
For example a should print:
{'Key2.b': '3', 'Key1': '1', 'Key2.c.d': '3', 'Key2.a': '2', 'Key2.c.e': '1'}
But right now the code randomly gives me back the correct answer but from a range of 0-5 such as
{'Key2.b': '3', 'Key1': '1', 'Key2.c.d': '3', 'Key2.a': '2'},
{'Key2.b': '3', 'Key2.c.d': '3'}
I found out that if i get rid of the "return" in my else statement it would work but i am not sure why that is? Can anybody help me with it
When you iterate over the keys in dict with for key in dict: it will return the keys in random order since elements in dictionaries aren't ordered. If Key1 is processed first it will be added to output and on the next iteration Key2 will be recursively processed. Now if the order is different and Key2 is processed first then return solution(dict[key],output,ini+key+'.') will cause the result to be returned before Key1 gets added to output. Same goes with nested elements within Key2. If you remove the return statement then all the keys will be processed no matter the iteration order and you'll get the expected output.
as you put the result in output, you should not return at else,otherwise, the for loop will break, and the rest keys will be ignored.(just remove return, and it will do work)

Correct way to change a list of strings to list of ints [duplicate]

This question already has answers here:
Can't modify list elements in a loop [duplicate]
(5 answers)
Closed 6 years ago.
dict = {0: ['2', '6'], 1: ['2'], 2: ['3']}
print("Original: ")
print(dict)
for key,vals in dict.items():
vals = [int(s) for s in vals]
print("New: ")
print(dict)
Output:
Original:
{0: ['2', '6'], 1: ['2'], 2: ['3']}
New:
{0: ['2', '6'], 1: ['2'], 2: ['3']}
I can't figure why the list of values is not changing, I have tried the map() function and it also does not work, any reason why?
In Python 3:
dict = {k: list(map(int, v)) for k, v in dict.items()}
Because you don't overwrite actually values in your dictionary. Try to do:
for key,vals in dict.items():
dict[key] = [int(s) for s in vals]
With dict comprehensions it looks much better, actually. I just tried to show what should be changed in your code.

Categories

Resources