Форум сайта python.su
I am having a doubt in a question
write a program to insert items at the beginning of the ordered dict.
Examples –
Input:
original_dict = {'a':1, ‘b’:2}
item to be inserted ('c', 3)
Output: {'c':3, ‘a’:1, ‘b’:2}
Input:
original_dict = {'akshat':1, ‘manjeet’:2}
item to be inserted ('nikhil', 3)
Output: {'nikhil':3, ‘akshat’:1, ‘manjeet’:2}
How to do this?
Офлайн
KonohaHokageCreate a new dict.
How to do this?
KonohaHokage
original_dict = {'a':1, ‘b’:2}
item to be inserted ('c', 3)
>>> dct = {'a': 1, 'b': 2} >>> item = ('c', 3) >>> >>> out = dict((item,) + tuple(dct.items())) >>> out {'c': 3, 'a': 1, 'b': 2} >>>
>>> dct = {'a': 1, 'b': 2} >>> item = ('c', 3) >>> >>> tmp = list(dct.items()) >>> tmp.insert(0, item) >>> out = dict(tmp) >>> out {'c': 3, 'a': 1, 'b': 2} >>>
Отредактировано py.user.next (Янв. 27, 2021 10:03:43)
Офлайн
py.user.next
Офлайн