I have a dictionary where I have the data already inside, i.e. keys have values and some of them have more than one value.
For example:
i = {"a": "111", "b": "222", "c": ["333", "444"]}
How can I change the type of the multiple values? I want them to be sets, not lists, such as:
i = {"a": {"111"}, "b": {"222"}, "c": {"333", "444"}}
One similar post is this one:
How to add multiple values to a dictionary key in python? [closed]
There it is explained how to add multiple elements to a dictionary, but they always seem to be lists.
How to change the type of the multiple values?
OR how to add them to the dictionary as sets, not lists?
Using a dict-comprehension makes converting an existing dict very easy:
i = {"a": "111", "b": "222", 'c': ["333", "444"]}
{k: set(v) if isinstance(v, list) else v for k, v in i.items()}
this converts all values that are lists to sets.
In a single line of code:
>>> i = {"a": "111", "b": "222", "c": ["333", "444"]}
>>> {k: set(v) for k, v in i.items()}
{'b': {'2'}, 'a': {'1'}, 'c': {'444', '333'}}
Or with a few more steps:
>>> i = {"a": "111", "b": "222", "c": ["333", "444"]}
>>> for k, v in i.items():
... i[k] = set(v)
>>> i
{'b': {'2'}, 'a': {'1'}, 'c': {'444', '333'}}
Instead of doing
my_dict['key'] = ['333', '444']
use a set literal:
my_dict['key'] = {'333', '444'}
That looks like a dict literal, but the lack of key: value like things makes it a set.
Related
To explain what I mean, I'm adding keys and values to a dictionary but if a key in the dictionary has a value that's the name of another key, I want that key to be assigned the other key's value. For example, if I have dict1 = {"a": 100, "b": 200, "c": "a"}
is it possible to change the value of c to 100 (which is a's value)? So instead it would be
dict1 = {"a": 100, "b": 200, "c": 100} The code I have right now is obviously wrong and giving me an error but I was trying to type out what I thought would work
for x, y in dict1.items():
if dict1[x] == dict1[x]:
dict1[x] = dict1[y]
print(x, y)
You can use:
my_dict = {"a": 100, "b": 200, "c": "a"}
for k, v in my_dict.items():
if v in my_dict:
my_dict[k] = my_dict[v]
You can alternatively use a dict comprehension:
result = {
k: my_dict[v] if v in my_dict else v
for k, v in my_dict.items()
}
Output:
{'a': 100, 'b': 200, 'c': 100}
"""
Given two dictionaries, find the keys they have in common,
and return a new dictionary that maps the corresponding values.
Example:
dict1 == {"a":"alpha", "d":"delta", "x":"xi"}
dict2 == {"b":"bet", "d":"dalet", "l":"lamed", "a":"alef"}
should return:
{"alpha":"alef", "delta":"dalet", "beta":"bet"}
"""
dict1 == {"a":"alpha", "d":"delta", "x":"xi"}
dict2 == {"b":"bet", "d":"dalet", "l":"lamed", "a":"alef"}
new_dict = {}
for key, value in dict1.items():
if value in new_dict:
new_dict[value].append(key)
else:
new_dict[value]=[key]
This is what I have, all I have to do is make it so that the output is what is the same as {"alpha":"alef", "delta":"dalet", "beta":"bet"} which is just switching the keys.
According to your question if two dictionaries are like this:
dict1= {"a":"alpha", "d":"delta", "x":"xi"}
dict2 == {"b":"bet", "d":"dalet", "l":"lamed", "a":"alef"}
comm_keys = set(dict1.keys()).intersection(dict2.keys())
required_dict = {dict1[key]: dict2[key] for key in comm_keys}
# Expected output : {'delta': 'dalet', 'alpha': 'alef'}
One more way which you can do this is to use dictionary comprehension
dict1 = {"a": "alpha", "d": "delta", "x": "xi"}
dict2 = {"b": "bet", "d": "dalet", "l": "lamed", "a": "alef"}
output = {dict1[x]: dict2[x] for x in dict1 if x in dict2}
{'alpha': 'alef', 'delta': 'dalet'}
Using dictionary comprehension is it possible to convert all values recursively to string?
I have this dictionary
d = {
"root": {
"a": "1",
"b": 2,
"c": 3,
"d": 4
}
}
I tried
{k: str(v) for k, v in d.items()}
But the code above turns the entire root value into string and I want this:
d = {"root": {"a": "1", "b": "2", "c": "3", "d": "4"}}
This is not a dictionary comprehension, but it works, it's just one line, and it's recursive!
(f := lambda d: {k: f(v) for k, v in d.items()} if type(d) == dict else str(d))(d)
It only works with Python 3.8+ though (because of the use of an assignment expression).
You could do a recursive solution for arbitrarily nested dicts, but if you only have 2 levels the following is sufficient:
{k: {k2: str(v2) for k2, v2 in v.items()} for k, v in d.items()}
Assuming that your given input was wrong and root's value was a dictionary, your code would somewhat work. You just need to add d['root'].items()
newDict = {k:{k: str(v) for k, v in d[k].items()} for k,v in d.items()}
output
{'root': {'a': '1', 'b': '2', 'c': '3', 'd': '4'}}
The following solution might not be using dictionary comprehension, but it is recursive and can transform dictionaries of any depth, I don't think that's possible using comprehension alone:
def convert_to_string(d):
for key, value in d.items():
if isinstance(value, dict):
convert_to_string(value)
else:
d[key] = str(value)
Found a simpler way to to achieve this using json module. Just made the following
import json
string_json = json.dumps(d) # Convert to json string
d = json.loads(string_json, parse_int=str) # This convert the `int` to `str` recursively.
Using a function
def dictionary_string(dictionary: dict) -> dict:
return json.loads(json.dumps(dictionary), parse_int=str, parse_float=str)
Regards
Is there a convenient way to map a function to specified keys in a dictionary?
Ie, given
d = {"a": 1, "b": 2, "c": 3}
would like to map a function, say f, to keys "a" and "c":
{"a": f(1), "b": 2, "c": f(3)}
EDIT
Looking for methods that will not update the input dictionary.
You can use a dictionary comprehension:
output_dict = {k: f(v) for k, v in d.items()}
Note that f(v) will be evaluated (called) immediately and its return values will be stored as the dictionary's values.
If you want to store the function and call it later (with the arguments already stored) you can use functools.partial:
from functools import partial
def f(n):
print(n * 2)
d = {"a": 1, "b": 2, "c": 3}
output_dict = {k: partial(f, v) for k, v in d.items()}
output_dict['b']()
# 4
If you only want specific keys mapped you can of course not use .items and just override those keys:
d['a'] = partial(f, d['a'])
or more generalized
keys = ('a', 'c')
for key in keys:
d[key] = partial(f, d[key])
I have a string that could be parsed as a JSON or dict object. My string variable looks like this :
my_string_variable = """{
"a":1,
"b":{
"b1":1,
"b2":2
},
"b": {
"b1":3,
"b2":2,
"b4":8
}
}"""
When I do json.loads(my_string_variable), I have a dict but only the second value of the key "b" is kept, which is normal because a dict can't contain duplicate keys.
What would be the best way to have some sort of defaultdict like this :
result = {
"a": 1,
"b": [{"b1": 1, "b2": 2}, {"b1": 3, "b2": 2, "b4": 8}],
}
I have already looked for similar questions but they all deal with dicts or lists as an input and then create defaultdicts to handle the duplicate keys.
In my case I have a string variable and I would want to know if there is a simple way to achieve this.
something like the following can be done.
import json
def join_duplicate_keys(ordered_pairs):
d = {}
for k, v in ordered_pairs:
if k in d:
if type(d[k]) == list:
d[k].append(v)
else:
newlist = []
newlist.append(d[k])
newlist.append(v)
d[k] = newlist
else:
d[k] = v
return d
raw_post_data = '{"a":1, "b":{"b1":1,"b2":2}, "b": { "b1":3, "b2":2,"b4":8} }'
newdict = json.loads(raw_post_data, object_pairs_hook=join_duplicate_keys)
print (newdict)
Please note that above code depends on value type, if type(d[k]) == list. So if original string itself gives a list then there could be some error handling required to make the code robust.
Accepted answer is perfectly fine. I just wanted to show another approach.
So at first, you dedicate a list for values in order to easily accumulate next values. At the end, you call pop on the lists which have only one item. This means that the list doesn't have duplicate values:
import json
from collections import defaultdict
my_string_variable = '{"a":1, "b":{"b1":1,"b2":2}, "b": { "b1":3, "b2":2,"b4":8} }'
def join_duplicate_keys(ordered_pairs):
d = defaultdict(list)
for k, v in ordered_pairs:
d[k].append(v)
return {k: v.pop() if len(v) == 1 else v for k, v in d.items()}
d = json.loads(my_string_variable, object_pairs_hook=join_duplicate_keys)
print(d)
output:
{'a': 1, 'b': [{'b1': 1, 'b2': 2}, {'b1': 3, 'b2': 2, 'b4': 8}]}