1

Suppose I have a list li=['project1','project2','project3'] I want to add these values as key to dictionary and value of first key should be completed rest onhold

projects can be any and value of first project in list should be completed rest onhold output required:

dict={'project1':'completed','project2':'onhold','project3':'onhold'}
li=['project1','project2','project3']
for trav_cont in li:
   dict[trav_cont]='completed'  
1
  • 1
    You can use zip(): my_dict = dict(zip(li, ('completed',) + ('onhold',) * (len(li) - 1))). Do not use dict as name of variable, you're shadowing build-in function. Commented Nov 10, 2020 at 12:11

3 Answers 3

5

You might use enumerate to know position in list, i.e.:

li=['project1','project2','project3']
dct = {i: 'completed' if inx==0 else 'onhold' for inx, i in enumerate(li)}
print(dct) # {'project1': 'completed', 'project2': 'onhold', 'project3': 'onhold'}

I used so-called dict-comprehension here, combined with ternary if, so value is 'completed' if its first element (has index 0 as python indices are 0-based) else 'onhold'

Sign up to request clarification or add additional context in comments.

Comments

3

You can create a dictionary with predetermined keys and a default value:

my_dict = dict.fromkeys(li, 'onhold')
my_dict['project1'] = 'completed'

Gives:

{'project1': 'completed', 'project2': 'onhold', 'project3': 'onhold'}

3 Comments

This is the cleanest answer.
But the name will not always be project1 it should be dynamic
@shee8, you can use my_dict[next(iter(my_dict))] = 'completed' to set value for first key. (It will work only on python 3.6+)
1
for idx, key in enumerate(li):
    if idx == 0:
        dixt[key] = 'completed'
        continue
    dict[key] = 'onhold'

1 Comment

Just use else, you don't need continue there.

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.