I have a dictinary
dict1 = {"one":"1", "two":"2", "three":"3", "four":"4", "five":"5"}
now I want another dictionary say dict2
which contains second and third element of dict1
How can I do this please help Thanks
I have a dictinary
dict1 = {"one":"1", "two":"2", "three":"3", "four":"4", "five":"5"}
now I want another dictionary say dict2
which contains second and third element of dict1
How can I do this please help Thanks
dict2 = {}
pos = 0
for x in dict1:
if(pos == 1 or pos == 2):
dict2[x] = dict1[x]
pos += 1
in a single line
dict2, positions = {}, (2, 3)
[dict2.update({key: dict1[key]}) for i, key in enumerate(dict1.keys()) if i in positions]
print(dict2)
Here's a one-liner using .items()
to get an iterable of (key, value)
pairs, and the dict
constructor to build a new dictionary out of a slice of those pairs:
>>> dict(list(dict1.items())[1:3])
{'two': '2', 'three': '3'}
The slice indices are 1 (inclusive) and 3 (exclusive) since indices count from 0. Note that this uses whatever order the items are in the original dictionary, which will be the order they were inserted in (unless using an old version of Python, in which case the order is generally non-deterministic). If you want a different order, you can use sorted
instead of list
, perhaps with an appropriate key
function.
Try this -
dict1 = {"one":"1", "two":"2", "three":"3", "four":"4", "five":"5"}
dict2 = {}
list1 = ['two','three'] # The elements you want to copy
for key in dict1:
if key in list1:
dict2[key] = dict1[key]
print(dict2)
Result:
{'two': '2', 'three': '3'}
Or alternatively -
for i in list1:
dict2[i] = dict1[i]
print(dict2)