Найти - Пользователи
Полная версия: Python query
Начало » Python для новичков » Python query
1
KonohaHokage
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?
py.user.next
KonohaHokage
How to do this?
Create a new dict.

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}
>>>
KonohaHokage
py.user.next

Thankyou !!
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB