1

Trying to convert an list to dictionary but could no get expected output

p = {}
a = ["s","l","y"]
for s in a:
    p["size"] = s

print(p)

output:

{'size': 'y'}

but i am expecting output like this

{'size': 's','size': 'l','size': 'y'}

how could i acheive this in python

4
  • 1
    No it cant, dict key should be unique Commented Apr 8, 2015 at 8:04
  • Yeah that's just not going to work as itzmeontv said. What is it that you're trying to do with the data? Commented Apr 8, 2015 at 8:05
  • Suppose you have the dict p you're trying to create, and you do p['size']. What do you want to happen? Commented Apr 8, 2015 at 8:11
  • If my answer answered your question. Please think of accepting it. Thanks! Commented Apr 8, 2015 at 8:21

3 Answers 3

2

You can't have multiple same keys in a dictionary, so you can use a list of dictionaries. A simple list comprehension should do the trick.

p = [{'size': a_size} for a_size in a]

Result :

[{'size': 's'}, {'size': 'l'}, {'size': 'y'}]
Sign up to request clarification or add additional context in comments.

1 Comment

You people should wait for a sec before down-voting anything. Let, the guy edit some stuff.
1

You can't achieve your goal since you are using a dictionary, and each key in a dictionary is unique. Perhaps you want to use a list instead:

p = []
a = ['s', 'l', 'y']
for s in a:
    p.append(('size',  s))

print(p)

Output:

[('size', 's'), ('size', 'l'), ('size', 'y')]

1 Comment

With this answer we converted a list into a list of nested tuples which doesn't match the dictionary as requested.
0

The following code should be a clean solution.

p = {}
a = ["s", "l","y"]
for s in a:
    if s == "s":
        p["small-size"] = s
    elif s == "l":
        p["large-size"] = s
    else:
        p["youth-size"] = s

print(p)

With the following output:

{'small-size': 's', 'large-size': 'l', 'youth-size': 'y'}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.