This question already has answers here:
How do I merge two dictionaries in a single expression in Python?
(43 answers)
Closed 4 years ago.
Hello, everyone.
Is there a way in python to insert all items from one dictionary to another inside variable assignment?
dict1 = {"a": 1, "b": 2, "c": 3}
dict2 = {"d": 4, #INSERT THERE ALL FROM "dict1"#, "e": -1}
Maybe there's smth like {key: value for key, value in temp.items()} or other "hack"?
I know that there's update() method and I've already applied it, but it looks a bit weird. Order of entries matters so to build dict in proper order I need to write next code :
dict1 = {"a": 1, "b": 2, "c": 3}
dict2 = {"d: 4"}
dict2.update(dict1)
dict2.update({"e": -1, "f": -2})
Hope there's a way to do it more "nice".
dict2 = {"d": 4, **dict1, "e": -1}
Related
Let's say I have a dictionary like below
myDict = {"a": 1, "b": 2, "c": 3, "d": 4}
and I'm trying to get this result
myDict = {"b": 1, "a": 2, "c": 3, "d": 4}
I tried running using
dictionary[new_key] = dictionary.pop(old_key)
But thats just deleting and appending a new key and value to the dictionary. It would result in:
myDict = {"b": 2, "c": 3, "d": 4, "a": 2}
Thanks in advance for the answer
So I understand you aim to preserve the sequence.
Make first a new dictionary that maps the old keys to the new keys:
mapping = {"a": "b", "b": "a"}
Now you can generate the new structure
my_dict = {mapping.get(key, key): value for key, value in my_dict.items()}
The get method here tries to map the key, but uses the key itself, if the key is not in the mapping.
This question already has answers here:
List of lists changes reflected across sublists unexpectedly
(17 answers)
Closed 3 years ago.
This behavior in Python 3.7.2 (did not check other versions) surprises me. The goal is to have a list of dictionaries with the same keys and be able to manipulate individual values. Using list index and dictionary key, the expected behavior is that I should be able to set value of a key of a specific dictionary.
Here's a sample code:
lst = []
lst.append({"A" : 0, "B" : 0 })
lst.append({"A" : 0, "B" : 0 })
lst[1]["B"] = 11
print(lst)
lst2 = [{"A" : 0, "B" : 0 }]*2
lst2[1]["B"] = 11
print(lst2)
Here's the result:
[{'A': 0, 'B': 0}, {'A': 0, 'B': 11}]
[{'A': 0, 'B': 11}, {'A': 0, 'B': 11}]
The second result surprises me, why would it set value of key "B" to 11 for both dictionaries? Why is there a difference between initializing as lst and lst1.
If you duplicate the dictionary - either the way you did, or a = b = {'someKey': 'someValue'}, you only copy the reference, and not the object itself. Changing the object through the reference will reflect the changes in the other references of the same object.
This question already has answers here:
Maintain order when dumping dict to JSON
(2 answers)
Call int() function on every list element?
(8 answers)
Closed 5 years ago.
I am writing a a REST API in python3 using flask and I have struggled to find a way to return a dict as json while maintaining the order of the keys. I am using an OrderedDict because obviously the built in dictionary does not preserve order of elements.
I have a method that looks like this:
#app.route('/foobar', methods=['GET'])
def foobar()
data = [OrderedDict([("a",1),
("b",2),
("c",3)])]
return jsonify(data),200
And here is an example of the output I could get:
[{"b":2,"c":3,"a":1}]
This is what I want to get:
[{"a":1,"b":2,"c":3}]
How can I return JSON in the order that its defined in the ordered dict?
Edit:
This is not a duplicate because the linked post is only for a dictionary I need this to work for a list of dictionaries
According to RFC7159, JavaScript Object Notation (JSON) is a text format for the serialization of structured data. It is derived from the object literals of JavaScript, as defined in the ECMAScript Programming Language Standard, Third Edition [ECMA-262].
An object is an unordered collection of zero or more name/value
pairs, where a name is a string and a value is a string, number,
boolean, null, object, or array.
An array is an ordered sequence of zero or more values.
For make order for your json you can use this:
#app.route('/')
def foobar():
data = OrderedDict([("a",1), ("z",2), ("c",3)])
return json.dumps([data])
Output
[{"a": 1, "z": 2, "c": 3}]
If sort_keys is true (default: False), then the output of dictionaries will be sorted by key.
For sorting, You can change your code to this:
#app.route('/foobar', methods=['GET'])
def foobar()
data = [OrderedDict([("a",1),
("z",2),
("c",3)])]
return json.dumps(data, sort_keys=True)
Output
[{"a": 1, "c": 3, "z": 2}]
Your problem is that the OrderedDict keeps insertion order for newly added/modified key/value pairs.
It's all down to how you get the key/values in the dictionary.
If you pass standard **kwargs, you will fail.
If the elements are passed as an iterable (as seen in your example) or later inserted, the order will be preserverd.
Standard kwargs
d = OrderedDict(a=1, b=2, c=3)
data = [d]
print(json.dumps(data))
Output:
[{"a": 1, "c": 3, "b": 2}]
Wrong order.
But with an iterable
d = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
data = [d]
print(json.dumps(data))
Output:
[{"a": 1, "b": 2, "c": 3}]
Order has been preserved.
Manual insertion
d = OrderedDict()
d['a'] = 1
d['b'] = 2
d['c'] = 3
data = [d]
print(json.dumps(data))
Output:
[{"a": 1, "b": 2, "c": 3}]
And order has been preserved again
This question already has answers here:
switching keys and values in a dictionary in python [duplicate]
(10 answers)
Closed 6 years ago.
I am currently preparing for a python exam and one topic we are expected to understand is having to flip a dictionary in which values become the keys and the keys become values. I am confused as to what this asking and if someone could provide me with a basic example to see what it looks like I would greatly appreciate it.
Simply write a dict comprehension expression and make it's key as value and values as key. For example:
>>> my_dict = {1: 2, 3: 4, 5: 6}
>>> {value: key for key, value in my_dict.items()}
{2: 1, 4: 3, 6: 5}
Note: Since, dict contains unique keys. In case you have same element as value for multiple keys in your original dict, you will loose related entries. For example:
# Same values v v
>>> my_dict = {1: 2, 3: 4, 5: 2}
>>> {value: key for key, value in my_dict.items()}
{2: 5, 4: 3}
#^ Only one entry of `2` as key
This question already has answers here:
Why doesn't a python dict.update() return the object?
(11 answers)
Closed 6 years ago.
I have the following Python script where I merge two dictionaries:
dict1 = {'bookA': 1, 'bookB': 2, 'bookC': 3}
dict2 = {'bookC': 2, 'bookD': 4, 'bookE': 5}
print dict2.update(dict1)
Why do I get as output None rather than the merged dictionaries? How can I display the result?
Thanks.
update does not return a new dictionary.
Do this instead:
dict1 = {'bookA': 1, 'bookB': 2, 'bookC': 3}
dict2 = {'bookC': 2, 'bookD': 4, 'bookE': 5}
dict2.update(dict1)
print(dict2)
dict2.update(dict1) updates dict2, but doesn't return it. Use print dict2 instead.