Goutam
Goutam

Reputation: 423

How to convert values of a dictionary list into string?

How to convert values of a dictionary list into string?

My dict:

dic = {3: ['W'], 2: ['X'], 1: ['Y', 'Z']}

I want output to be as below:

out_dic = {3: 'W', 2: 'X', 1: ['Y', 'Z']}

I tried with below, but not working. Can anyone help me out in this:

out_dic = {}
for key, value in dic.items():
    if (key == 1) | (key == 2):
        out_dic[key].append(value.ToString())
    else:
        out_dic[key].append(out_dic(i))
        
print(out_dic)

Upvotes: 0

Views: 132

Answers (2)

Sivaram Rasathurai
Sivaram Rasathurai

Reputation: 6333

Let's take the element of list which contains only one element and put that element as value of dic key.

for key,val in dic.items():
 if len(val)==1:
    dic[key] =val[0]
print(dic)

Upvotes: 1

Rakesh
Rakesh

Reputation: 82755

Using a dict comprehension. And using len() on value to find size.

Ex:

dic = {3: ['W'], 2: ['X'], 1: ['Y', 'Z']}
print({k: v[0] if len(v) == 1 else v for k, v in dic.items()})

Output:

{3: 'W', 2: 'X', 1: ['Y', 'Z']}

Upvotes: 2

Related Questions