Dylan
Dylan

Reputation: 113

making a list into dictionary

suppose you have a list

A = ["A: 1", "B: 2", "C: 3"]

can you make this into a dictionary of

dict_A = {"A" : 1, "B": 2, "C": 3} 

I got stuck at making the list into a dictionary

Upvotes: 1

Views: 77

Answers (3)

Zach Sonnenblick
Zach Sonnenblick

Reputation: 31

One nice way of doing this:

A = ["A: 1", "B: 2", "C: 3"]

A = [item.split(':') for item in A]
dict_A = dict([[key, int(val)] for key, val in A])

print(dict_A)  
>>  {'A': 1, 'B': 2, 'C': 3}

to break down each line and what it returns:

A = [item.split(':') for item in A]
>> [['A', ' 1'], ['B', ' 2'], ['C', ' 3']]  

After first splitting on :, each index in A now holds a list of two items. and each index of A can be unpacked. For example: first, second = A[1] is the same as first, second = A[1][0], A[1][1] ; in both cases 'B' would be assigned to first and '2' to second
Considering that all the numbers are still strings they need to be converted to int, but we only want to convert the second item in each of our nested lists; this is where unpacking can be useful, as we would only apply the int conversion to the second item.

This can be done nicely in a single list comprehension

[[key, int(val)] for key, val in A]
>> [['A', 1], ['B', 2], ['C', 3]]  

but, considering that you want a dictionary, we can just call dict() to convert into dictionary

dict([['A', 1], ['B', 2], ['C', 3]])
>> {'A': 1, 'B': 2, 'C': 3}

Upvotes: 0

Hasibul Islam Polok
Hasibul Islam Polok

Reputation: 105

A = ["A: 1", "B: 2", "C: 3"]
B={}
for i in A:
    B[i[0]]=int(i[3])
print(B)

{'A': 1, 'B': 2, 'C': 3}

the length of every string here is 4. the i[0] is the key like 'A' and the i[3] is the value like '1'. converting it to int would give you the exact value you want, and then you just assign it to the dictionary for each key values.

Upvotes: 1

inspectorG4dget
inspectorG4dget

Reputation: 113915

In [1]: A = ["A: 1", "B: 2", "C: 3"]

In [2]: {k:int(v.strip()) for k,v in (i.split(":") for i in A)}
Out[2]: {'A': 1, 'B': 2, 'C': 3}

This can effectively be unpacked as follows:

d = {}
for item in A:  # the first time around, item = "A: 1"
    key, value = item.split(":")  # key = "A", value = " 1"
    value = value.strip()  # value = "1"
    value = int(value)  # value = 1
    d[key] = value

Upvotes: 6

Related Questions