How to append to a Python dictionary instead of updating [duplicate] - python

This question already has answers here:
How can one make a dictionary with duplicate keys in Python?
(9 answers)
Closed 3 years ago.
I would like to append to a dictionary for e.g
a={1:2}
a.update({2:4})
a.update({1,3})
I would like this to give
a ={1: (2,3), 2: 4}
How can this be done? There is no append. Update overwrites this as
{1: 3, 2: 4}
Please let me know

You could try something like this:
a = {1:2}
updates = [{2:4},{1:3}]
for dct in updates:
for key in dct:
if key in a:
a[key] = (a[key], dct[key])
else:
a[key] = (dct[key])
print(a)
#Gives: {1: (2, 3), 2: 4}

Related

Is there a shorter way of doing this in python? [duplicate]

This question already has answers here:
Python Dictionary Comprehension [duplicate]
(9 answers)
Closed 8 months ago.
Is there a shorter way to perform an operation on each dictionary item, returning a new dictionary without having to first create an empty dictionary like i did?
Note: The original a_dictionary values should not be changed.
a_dictionary = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
result_dict = {}
result_dict.update((x, y*2) for x, y in a_dictionary.items())
You can use dict comprehension:
result_dict = {x: y*2 for x, y in a_dictionary.items()}

Access dict values by function parameter [duplicate]

This question already has answers here:
Can't modify list elements in a loop [duplicate]
(5 answers)
Closed 9 months ago.
I am trying to write a function replace(d, v, e) where d is a dict and v and e are ints. The function is supposed to replace all dictionary values of v to e.
This code works fine:
def replace(d, v, e):
for key, value in d.items():
if value == v:
d[key] = e
return d
print(replace({1:2, 3:4, 4:2}, 2, 7)) # output: {1: 7, 3: 4, 4: 7}
But when I alter the code to change the value using d.values(), it doesn't work:
def replace(d, v, e):
for i in d.values():
if i == v:
i = e
return d
print(replace({1:2, 3:4, 4:2}, 2, 7)) # output: {1: 2, 3: 4, 4: 2}
May I have any advice on how to modify the 2nd code to make it work like the 1st code?
Modifying the second code "to work" would require using items in place of values, so in short, you cannot modify the value without knowing the key. What your second code does is only to assign the value to i locally in the function without ever affecting the dictionary.
Another remark, your first version of the function modifies the dictionary in place and returns it, which is not a really good practice, you should do either the one or the other.
Finally, here is a version to return a new dictionary without changing the input, using a dictionary comprehension:
def replace(d, v, e):
return {k: e if val==v else val for k,val in d.items()}
replace({1: 2, 3: 4, 4: 2}, 2, 7)
# {1: 7, 3: 4, 4: 7}

Print all dictionaries and a variables [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed last year.
I have like 10 dictionaries and I want to print all the dictionaries with all the keys inside.
Dict1 = {}
...
Dict10 = {}
We could do:
print(list(Dict1.keys()))
...
print(list(Dict10.keys()))
But is there a code more simple to do this? Like a for loop?
I'm working on a project where:
Operator types get_report
The program looks for all dictionaries in another .py file and print all the keys from every dictionary
In python globals() store all variable as a dictionary
dict1 = {1: 1, 2: 2}
dict2 = {6: 1, 7: 2}
dict3 = {4: 1, 3: 2}
var = globals()
for i in range(1, 11):
dict_name = f"dict{i}"
if var.get(dict_name):
keys = var[dict_name].keys()
print(list(keys))
#timegb suggested this might get crashed. So better approach to use dict.get to handle unknown keys

How to take several items from dictionary [duplicate]

This question already has answers here:
Extract a subset of key-value pairs from dictionary?
(14 answers)
Filter dict to contain only certain keys?
(22 answers)
Closed 5 years ago.
Dictionary:
d = {'a':[2,3,4,5],
'b':[1,2,3,4],
'c':[5,6,7,8],
'd':[4,2,7,1]}
I want to have d_new which containes only b and c items.
d_new = {'b':[1,2,3,4],
'c':[5,6,7,8]}
I want a scalable solution
EDIT:
I also need a method to create a new dictionary by numbers of items:
d_new_from_0_to_2 = {'a':[2,3,4,5],
'b':[1,2,3,4]}
If you want a general way to pick particular keys (and their values) from a dict, you can do something like this:
d = {'a':[2,3,4,5],
'b':[1,2,3,4],
'c':[5,6,7,8],
'd':[4,2,7,1]}
selected_keys = ['a','b']
new_d = { k: d[k] for k in selected_keys }
Gives:
{'a': [2, 3, 4, 5], 'b': [1, 2, 3, 4]}
I think that in Python 2.6 and earlier you would not be able to use a dict comprehension, so you would have to use:
new_d = dict((k,d[k]) for k in selected_keys)
Is this what you want?
new_d = dict(b=d.get('b'), c=d.get('c'))

Iterating over an `OrderedDict` and deleting some of its keys? [duplicate]

This question already has an answer here:
deleting entries in a dictionary based on a condition
(1 answer)
Closed 6 years ago.
Suppose I have an OrderedDict od with integer keys and integer values. I want to iterate over od and delete elements of od based on the value I find. Basically what I want to achieve is:
od = {1: 2, 2: 4, 3: 5}
for key in od:
del od[key]
In the end I want od to be equal to {1: 2, 3: 5}. Python does not allow to change the size of an OrderedDict during its iteration. Is it possible to overcome this problem?
I am working with Python 3.5
That is because you can not modify the length of dict while you are iterating over it. Instead you have to iterate over the copy of list of keys within the dict as:
# For both Python 3.x and 2.7
>>> for key in list(od):
... del od[key]
...
>>> od
{}
However in Python2.7, one may even use dict.keys() to get the same behavior:
# In Python 2.7
>>> for key in od.keys():
... del od[key]
...
>>> od
{}
this is the easiest way i know. enjoy!
With dicts, you can't change the length of the dictionary. however, what you can do is make a list copy of the original dictionary and use that to iterate through the original dictionary. as shown below
od = {'a': 2, 'b': 4, 'c': 5}
for key in list(od):
if key == 'b':
print(key)
del od[key]
print(od)
I think this what you mean to do
od = {1: 2, 2: 4, 3: 5}
for key in od.copy(): # iterate over a copy
if key in od and od[key] in od: # check for both key, 'target' key
del od[od[key]] # then delete the target with indirect indexing
od
Out[52]: {1: 2, 3: 5}

Categories