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
Related
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()}
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}
This question already has answers here:
Access nested dictionary items via a list of keys?
(20 answers)
Closed 4 years ago.
If I have a nested dictionary
mydict={'a1':{'b1':1}, 'a2':2}
and a list of indexes index = ['a1', 'b1'] leading to an inner value, is there a pythonic / one-liner way to get that value, i.e. without resorting to a verbose loop like:
d = mydict
for idx in index:
d = d[idx]
print(d)
You can use functools.reduce.
>>> from functools import reduce
>>> mydict = {'a1':{'b1':1}, 'a2':2}
>>> keys = ['a1', 'b1']
>>> reduce(dict.get, keys, mydict)
1
dict.get is a function that takes two arguments, the dict and a key (and another optional argument not relevant here). mydict is used as the initial value.
In case you ever need the intermediary results, use itertools.accumulate.
>>> from itertools import accumulate
>>> list(accumulate([mydict] + keys, dict.get))
[{'a1': {'b1': 1}, 'a2': 2}, {'b1': 1}, 1]
Unfortunately, the function does not take an optional initializer argument, so we are prepending mydict to keys.
This question already has answers here:
Initialize List to a variable in a Dictionary inside a loop
(2 answers)
Closed 5 years ago.
I have a dictionary that needs to create a key when the key first shows up and adds a value for it, later on, keeps updating the key with values by appending these values to the previous value(s), I am wondering how to do that.
outter_dict = defaultdict(dict)
num_index = 100
outter_dict['A'].update({num_index: 1})
outter_dict['A'].update({num_index: 2})
2 will replace 1 as the value for key 100 of the inner dict of outter_dict, but ideally, it should look like,
'A': {100:[1,2]}
UPDATE
outter_dict = defaultdict(list)
outter_dict['A'][1].append(2)
but I got
IndexError: list index out of range
if I do
dict['A'][1] = list()
before assign any values to 1, I got
IndexError: list assignment index out of range
You can use a collections.defaultdict:
from collections import defaultdict
d = defaultdict(list)
num_index = 100
d[num_index].append(1)
d[num_index].append(2)
print(dict(d))
Output:
{100: [1, 2]}
Regarding your most recent edit, you want to use defautldict(dict) and setdefault:
outter_dict = defaultdict(dict)
outter_dict["A"].setdefault(1, []).append(2)
print(dict(outter_dict))
Output:
{'A': {1: [2]}}
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'))