0

I want to add to the first key of a dict the first element of a list, same for the second and so on. How can I do that?

d = {'a_': 1, 'b_': 2}
l = ['orange', 'apple']

I would like to get:

d = {'a_orange': 1, 'b_apple': 2}

I tried: A = [{f'{k}{items}': v for k, v in d.items() for j in l}

but this produce: ['a_orange', 'a_apple', 'a_orange', 'a_apple'] which is not what I am looking for.

Newbie
  • 451
  • 1
  • 3
  • 14
  • 1
    dictionaries are not sorted, there's no such thing as "first key of a dict". –  Jan 28 '22 at 14:18
  • You're looping over the list for each element in the dict. You should use something like ```zip``` to loop over the dict and the list at the same time – Metapod Jan 28 '22 at 14:19
  • @SembeiNorimaki thats not true as of Python 3.7 and greater they are ordered: https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6#:~:text=Dictionaries%20are%20ordered%20in%20Python,short%20paragraph%20in%20the%20documentation. – Andreas Jan 28 '22 at 14:20
  • yes, but not sorted as they would expect. try it with `d = {'a_': 2, 'b_': 1}` –  Jan 28 '22 at 14:22
  • @SembeiNorimaki Sorted and ordered are not the same thing. – Metapod Jan 28 '22 at 14:24

1 Answers1

2

Try dict comprehension with zip but this assumes that d and l are the same length and there is only one value for each key in d

d = {'a_': 1, 'b_': 2}
l = ['orange', 'apple']

{d[0]+l:d[1] for d,l in zip(d.items(),l)} # -> {'a_orange': 1, 'b_apple': 2}
It_is_Chris
  • 13,504
  • 2
  • 23
  • 41