1

Set-Up

I create dictionaries in a loop, all containing the same keys but different values.

A part of one of the dictionaries as example,

data = {
        'type': 'An apartment',
        'sublet': 'Indifferent',
       }

At the end of the loop, I append the values of each dictionary data to a 'large' dictionary all_data.

I create all_data = {} before commencement of the loop.


Problem

When I append the values of data to all_data, Python splits the string values of data into characters. E.g.

all_data {
         'type': ['A', 'n', ' ', 'a', 'p', 'a', 'r', 't', 'm', 'e', 'n', 't'],
         'sublet': ['I', 'n', 'd', 'i', 'f', 'f', 'e', 'r', 'e', 'n', 't'],
         }

I append the values via the following code (which I found here),

for key, value in data.items():
     all_data.setdefault(key,[]).extend(value)  

How do I obtain,

all_data {
         'type': 'An apartment',
         'sublet': 'Indifferent',
         }

Such that after the loop is finished, I obtain,

all_data {
         'type': 'An apartment', 'A room', 'An apartment',
         'sublet': 'Indifferent', 'Yes', 'Yes'
         }

where order matters.

LucSpan
  • 1,831
  • 6
  • 31
  • 66
  • [here](https://stackoverflow.com/questions/26910708/merging-dictionary-value-lists-in-python) is a nice one-liner! – syntax Feb 11 '18 at 06:47

1 Answers1

3

You should use .append() not .extend().

for key, value in data.items():
    all_data.setdefault(key,[]).append(value)

.extend() extends the list with the given iterable. A string is an iterable of characters, therefore the target list will receive a single character as each item.

Bharel
  • 23,672
  • 5
  • 40
  • 80