0

Python question:

Why does this return a list of characters instead of a list of the keys as strings?

d = {'key1': 'aaa', 'key2': 'aaa', 'key3': 'bbb'}
a=[]

for k,v in d.items():
    a += k

print(a)

I received the following result:

['k', 'e', 'y', '1', 'k', 'e', 'y', '2', 'k', 'e', 'y', '3']

JoYKim
  • 11
  • 1

2 Answers2

1

Because the += operator in lists expects an iterable, resulting in a concatenation of that iterable into the list. A string is an iterable of its chars.

To have the results you expect, do either:

a.append(k)

or

a += [k]
Juan Lopes
  • 10,143
  • 2
  • 25
  • 44
0

Use append() to append k to a list:

d = {'key1': 'aaa', 'key2': 'aaa', 'key3': 'bbb'}
a=[]

for k,v in d.items():
    a.append(k)

print(a)
Arifa Chan
  • 947
  • 2
  • 6
  • 23