Python | Перетворити об’єкт словника на рядок
Словник є важливим контейнером і використовується майже в кожному коді повсякденного програмування, а також веб-розробки з Python . Чим більше він використовується, тим більша вимога, щоб оволодіти ним, і, отже, необхідно дізнатися про них.
Input: { 'testname' : 'akshat','test2name' : 'manjeet','test3name' : 'nikhil'} Output: {'testname': 'akshat', 'test2name': 'manjeet', 'test3name': 'nikhil'} Explanation: Input type is but the output type is Давайте розглянемо різні способи зміни словника на рядок.
Об'єкт словника в рядок Розмова
Нижче наведено методи, які ми розглянемо в цій статті.
- Використання json.dumps() метод
- Використання str() функція
- Використання спосіб друку
Перетворення Dict на String у Python за допомогою методу json.dumps().
Тут ми можемо використати метод dump() із JSON бібліотеку, імпортувавши її, яка перетворює тип даних словника на рядок. У наведеному нижче коді ми спочатку виконуємо словниковий тест1, а потім використовуємо json.dumps метод і передати в нього словник tes1, і ми отримаємо потрібний результат у рядок формат.
Python3
import> json> # initialising dictionary> test1> => {> 'testname'> :> 'akshat'> ,> > 'test2name'> :> 'manjeet'> ,> > 'test3name'> :> 'nikhil'> }> # print original dictionary> print> (> type> (test1))> print> (> 'initial dictionary = '> , test1)> # convert dictionary into string> result> => json.dumps(test1)> # printing result as string> print> (> '
'> ,> type> (result))> print> (> 'final string = '> , result)> |
Вихід:
initial dictionary = {‘testname’: ‘akshat’, ‘test2name’: ‘manjeet’, ‘test3name’: ‘nikhil’} final string = {testname: akshat, test2name: manjeet, test3name: nikhil} Складність простору: O(n)
Часова складність: O(n)
Перетворення словника в рядок за допомогою функції str().
The str() функція перетворює вказане значення в рядок. Функція string також корисна для перетворення типу даних у рядковий тип. Таким чином, ми передаємо словник у цей метод, і він перетворить словник типу даних у рядковий тип даних.
Python3
test1> => {> 'testname'> :> 'akshat'> ,> > 'test2name'> :> 'manjeet'> ,> > 'test3name'> :> 'nikhil'> }> # print original dictionary> print> (> type> (test1))> print> (> 'initial dictionary = '> , test1)> # convert dictionary into string> result> => str> (test1)> # print resulting string> print> (> '
'> ,> type> (result))> print> (> 'final string = '> , result)> |
Вихід:
initial dictionary = {‘test2name’: ‘manjeet’, ‘testname’: ‘akshat’, ‘test3name’: ‘nikhil’} final string = {‘test2name’: ‘manjeet’, ‘testname’: ‘akshat’, ‘test3name’: ‘nikhil’} Складність простору: O(n)
Часова складність: O(n)
Перетворіть словник на рядок за допомогою методу друку
Інший підхід до перетворення об'єкта словника в рядок полягає у використанні друку. Друк забезпечує спосіб довільного красивого друку Python структури даних у формі, яка друкувати можна використовувати як вхідні дані для інтерпретатора.
Ось приклад використання модуля print that для перетворення об’єкта словника в рядок:
Python3
import> pprint> # Initialize dictionary> d> => {> 'testname'> :> 'akshat'> ,> 'test2name'> :> 'manjeet'> ,> 'test3name'> :> 'nikhil'> }> # Print original dictionary> print> (f> 'Original dictionary: {d}'> )> # Convert dictionary into string using pprint.pformat()> result> => pprint.pformat(d)> # Print resulting string> print> (f> '
Resulting string: {result}'> )> print> (> 'Type is: '> ,> type> (result))> |
Вихід
Original dictionary: {'testname': 'akshat', 'test2name': 'manjeet', 'test3name': 'nikhil'} Resulting string: {'test2name': 'manjeet', 'test3name': 'nikhil', 'testname': 'akshat'} Type is: Space complexity : O(n) Time complexity : O(n) The print module provides more control over the formatting of the resulting string, such as indentation and line width, than the built-in str and json.dumps functions.