-4

I have two dictionaries,

var1 = {'name': 'alice'}
var2 = {'name': 'bob'}

I would like to concatenate these to produce,

var3 = {'name': 'alice'},{'name': 'bob'}

How is this achieved?

Samuel
  • 157
  • 6
  • 22
  • 2
    var1 and var2 are set, not a dictionary – Dima Kudosh Sep 21 '15 at 16:04
  • no.. that are not dictionaries. – Bastian Sep 21 '15 at 16:05
  • Do you mean `{'alice', 'bob'}` for var3? – interjay Sep 21 '15 at 16:05
  • 2
    and `var3` is currently a tuple. If you wanted to do that, well, `var3 = var1, var2` would work. – NightShadeQueen Sep 21 '15 at 16:06
  • You don't have the correct data type defined in your example. Also, you should make the dictionaries that you do correctly define more complex as your single value dictionaries are hiding multiple value complexities that your code will need to deal with. Dictionaries have `key,value` pairs, e.g. `dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};` – Shawn Mehan Sep 21 '15 at 16:06
  • possible duplicate of [How can I merge two Python dictionaries in a single expression?](http://stackoverflow.com/questions/38987/how-can-i-merge-two-python-dictionaries-in-a-single-expression) – Shawn Mehan Sep 21 '15 at 16:08
  • My mistake: The types of var1 and var2 are dictionaries, and the type of var3 is a tuple. – Samuel Sep 21 '15 at 16:08

2 Answers2

1

To add the key-value pairs of dict2 to the ones of dict1 you can use dict1.update(dict2). This modifies dict1 obviously though.

  • Please consider editing your post to add more explanation about what your code does and why it will solve the problem. An answer that mostly just contains code (even if it's working) usually wont help the OP to understand their problem. – SuperBiasedMan Sep 21 '15 at 17:02
  • Better is `dict3 = dict(dict1); dict3.update(dict2)`. Otherwise you mutate one of the original dicts. However this is all a moot point. OP really wanted a tuple of dictionaries, not a single dict. – Steven Rumbalski Sep 21 '15 at 19:05
-1

Thanks to NightShadeQueen for the correct solution:

To obtain var3, doing var3 = var1,var2 is the way to achieve this

Samuel
  • 157
  • 6
  • 22