1

I have a dict like this:

{1: ['1,2,3', '4,5,6', '7,8']}

the dict can be variable in the number of list items but always 1 dict item. How do I merge it to

{1: ['1,2,3,4,5,6,7,8']}

?

Thanks

2
  • Are you sure you need a list as the value? It will always contain only one element. Commented Oct 21, 2011 at 14:06
  • @MarkByers what options are there? Commented Oct 21, 2011 at 14:36

2 Answers 2

2
>>> d
{1: ['1,2,3', '4,5,6', '7,8'], 2: ['9,10', '11']}
>>> for k,v in d.iteritems():
...     d[k] = [",".join(v)]
...
>>> d
{1: ['1,2,3,4,5,6,7,8'], 2: ['9,10,11']}
Sign up to request clarification or add additional context in comments.

1 Comment

This works just as well with one dict item. The example merely showing that it can also handle multiple items if needed. BTW, wouldn't a simple variable suffice if you have only one item?
1

in your case, you just need concat a string.

But if you want to merge the collection, try this:

a = [1, 2, 3]
b = [3, 4, 5]
a.extend(b)
print a

[1, 2, 3, 3, 4, 5]

1 Comment

Not what I was after as the number of collections can vary and your code expects a fixed number - however, I like the simplicity and will keep it for future code.

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.