Python
 Computer >> コンピューター >  >> プログラミング >> Python

タプルのリストを辞書に変換するPythonプログラム


ここで1つのタプルが与えられます。私たちのタスクは、タプルを辞書に変換することです。この問題を解決するために、辞書メソッドsetdefault()を使用します。このメソッドには2つのパラメーターがあり、最初のパラメーターをキーに変換し、2番目のパラメーターを辞書の値に変換します。 Setdefault(key、value)は、キーを検索してその値を表示する関数です。

Input:
   [("Adwaita", 5), ("Aadrika", 5), ("Babai", 37),  ("Mona", 7), ("Sanj", 25), ("Sakya", 30)] 
Output:
   {'Adwaita': 5, 'Aadrika': 5, 'Babai': 37, 'Mona': 7, 'Sanj': 25, 'Sakya': 30}

アルゴリズム

Step 1: Tuple is given.
Step 2: To convert the first parameter to key and the second to the value of the dictionary.
Step 3: Setdefault (key, value) function searches for a key and displays its value and creates a new key with value if the key is not present.
Step 4: Using the append function we just added the values to the dictionary.

サンプルコード

# Python code to convert into dictionary 
def listtodict(A, di): 
   di = dict(A) 
   return di 

# Driver Code  
A = [("Adwaita", 5), ("Aadrika", 5), ("Babai", 37), ("Mona", 7), ("Sanj", 25), ("Sakya", 30)] 
di = {} 
print ("The Dictionary Is ::>",listtodict(A, di)) 

出力

The Dictionary Is ::> {'Adwaita': 5, 'Aadrika': 5, 'Babai': 37, 'Mona': 7, 'Sanj': 25, 'Sakya': 30}

  1. 文字のリストを文字列に変換するPythonプログラム

    Pythonはこの種の変換をたくさん必要とします。たとえば、このような変換はシリアル化の目的で役立ちます。このような変換の例は、-です。 ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] to "hello world" Pythonには、このような変換に使用できる結合メソッドがあります。オブジェクトを連結するために使用される区切り文字列

  2. Python辞書をリストに変換する方法は?

    Pythonの辞書クラスには、この目的のために3つのメソッドがあります。メソッドitems()、keys()、values()は、それぞれキーと値のペアのタプル、キーのみ、値のみで構成されるビューオブジェクトを返します。組み込みのlistメソッドは、これらのビューオブジェクトをリストオブジェクトに変換します。 >>> d1 = {name: Ravi, age: 23, marks: 56} >>> d1.items() dict_items([(name, Ravi), (age, 23), (marks, 56)]) >>> l1 =