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'))
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:
How do I extract all the values of a specific key from a list of dictionaries?
(3 answers)
Closed 4 years ago.
I need to get a list from the dictionaries which is in a list
I tried [v for k,v in l[i].iteritems() for i in len(l) if k=='cell']
Example:
l = [{'cell':4,'num':55}, {'cell':5,'num':66}, {'cell':6,'num':77}]
I want to write a nested for loop in a single line and get output as
output = [4,5,6]
l = [{'cell': 4, 'num': 55}, {'cell': 5, 'num': 66}, {'cell': 6, 'num': 77}]
ls = []
for i in l:
ls.append(i['cell'])
print(ls)
Try this
it should work like this:
l = [{'cell':4,'num':55}, {'cell':5,'num':66}, {'cell':6,'num':77}]
list_new=[]
for i in l:
list_new.append(i['cell'])
This question already has answers here:
How do I merge two dictionaries in a single expression in Python?
(43 answers)
Closed 5 years ago.
How would you go about converting a multi-line dictionary into one dictionary?
For example, the current dictionary, if printed to the screen, is of the form:
{'keyword':'value'}
{'keyword':'value'}
{'keyword':'value'}
{'keyword':'value'}
...and so on for over 100 hundred lines. How do you convert this to the following form:
{'keyword':'value','keyword':'value','keyword':'value','keyword':'value'}
Assuming you are asking for multiple dictionaries (not multiple line dictionary) to one dictionary.
a = {1: 1, 2:2}
b = {2:2, 3:3}
c = {2:3}
{**a, **b, **c}
Out: {1: 1, 2: 3, 3: 3}
Assuming that your initial data is actually a list of dictionaries and your keys are unique accross all your dictionaries I would use something like -
example = [{'a':1}, {'b':2}, {'c':3}]
objOut = {}
for d in example:
for k,v in d.iteritems():
objOut[k] = v
OR
objIn = [{'a':1}, {'b':2}, {'c':3}]
objOut = {}
for d in objIn:
objOut.update(d)
print objOut
Given
dicts = [{'a':1}, {'b':2}, {'c':3, 'd':4}]
Do
{k:v for d in dicts for (k, v) in d.items()}
or
from itertools import chain
dict(chain(*map(dict.items, dicts)))
resulting in
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
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]}}