Lets say I have a nested dictionary
nested_dict={"dict1":{"key1":"value1", "key2":"value2", "key3":"value3;value4"}}
Now I want to split value3 and value 4 under the same key like this,
nested_dict={"dict1":{"key1":"value1", "key2":"value2", 'key3': ['value3', 'value4']}}
What would be the best way to do so in Python?
use the fact that dict is mutable and you can recursively change anything under the sun :P
nested_dict={"dict1":{"key1":"value1", "key2":"value2", "key3":"value3;value4"}}
def sol(d):
for i in d:
if type(d[i]) is dict:
sol(d[i])
else:
d[i] = d[i].split(';')
if len(d[i])==1: d[i] = d[i][0]
sol(nested_dict)
print(nested_dict)
{'dict1': {'key1': 'value1', 'key2': 'value2', 'key3': ['value3', 'value4']}}
Related
I want to create a dictionary from a string that have key=value
s = "key1=value1 key2=value2 key3=value3"
print({r.split("=") for r in s})
Is it possible using dictionary comprehension? If yes, how?
You can first split on whitespace, then split on '='
>>> dict(tuple(i.split('=')) for i in s.split())
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
You could use map:
>>> s = "key1=value1 key2=value2 key3=value3"
>>> d = {k: v for k, v in map(lambda i: i.split('='), s.split())}
>>> {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
I have some records like that in collection:
{
'_id': 1,
'test_field': [{'key1': 'value1'}, {'key2': 'value2'}]
}
test_field is a list of dicts. I need to push new dict in that list if any key does not exist and if it does I need to update that key’s value.
Examples:
{'key1': 'test_value'} → 'test_field': [{'key1': 'test_value'}, {'key2': 'value2'}]
{'test_key': 'test_value2'} → 'test_field': [{'key1': 'value1'}, {'key2': 'value2'}, {'test_key': 'test_value_2'}]
Help please
if you need a function in python to do it, this might work for you.
def modify_test_field(my_dict, test_field, new_key, new_val):
my_dict[test_field] = [obj for obj in my_dict[test_field] if new_key not in obj]
my_dict[test_field].append({new_key: new_val})
and call it like modify_test_field(orig_dict, 'test_field', new_key, new_val)
There is a weird string representation like
"key1:value1:key2:value2:key3:value3...keyn:valuen"
I need to create a dict and it's pretty easy to solve when you have commas, however there is only colons here and you have to split the string every second colon. Code with cycle or soemthing like that looks pretty ugly, so I wonder if you could help me with oneliner.
You can just split on colons, get an iterator over the tokens and zip the iterator with itself. That will pair keys and values nicely:
s = 'key1:value1:key2:value2:key3:value3:keyn:valuen'
it = iter(s.split(':'))
dict(zip(it, it))
# {'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'keyn': 'valuen'}
If you are uncomfortable with iter (and schwobaseggls solutions wich I deem superior), you can use zipped list-slices in almost the same way:
s = 'key1:value1:key2:value2:key3:value3:keyn:valuen'
splitted = s.split(':')
# even_elements = splitted[::2] - take every 2nd starting at 0th index
# odd_elements = splitted[1::2] - take every 2nd startIng at 1st index
k = {k:v for k,v in zip(splitted[::2],splitted [1::2]) }
print(k)
Output:
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'keyn': 'valuen'}
Alternativly, you create the dict by hand:
s = 'key1:value1:key2:value2:key3:value3:keyn:valuen'
splitted = s.split(':')
d ={}
# this generates 2-slices from the list and puts them into your dict
for k,v in (splitted[i:i+2] for i in range(0,len(splitted),2)):
d[k] = v
# or d = { k:v for k, v in (splitted[i:i+2] for i in range(0,len(splitted),2) )}
# or d = dict(splitted[i:i+2] for i in range(0,len(splitted),2) )
print(d)
Output:
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'keyn': 'valuen'}
I have a dictionary like this
dict1 = {'key1': 'value1', 'key2': 'value2'}
how do I have an array of the keys and values as dictionaries like this
array_of_dict_values = [{'key1': 'value1'}, {'key2': 'value2'}]
What would be the easiest way to accomplish this?
You can do this:
>>> aDict = {'key1': 'value1', 'key2': 'value2'}
>>> aList = [{k:v} for k, v in aDict.items()]
>>> aList
[{'key2': 'value2'}, {'key1': 'value1'}]
While somebody already answered with how to do this, I'm going to answer with "you probably don't want to do this." If every entry is a dictionary with a single key, wouldn't a list of key-value pairs work just as well?
dictionary = {'key1': 'value1', 'key2': 'value2'}
print(list(dictionary.items()))
# [('key2', 'value2'), ('key1', 'value1')]
I have a list of dictionaries like:
dict_list = [{'key1': 'dict1_value1', 'key2': 'dict1_value2', 'key3': 'dict1_value3'},
{'key1': 'dict2_value1', 'key2': 'dict2_value2', 'key3': 'dict2_value3'},
{'key1': 'dict3_value1', 'key2': 'dict3_value2', 'key3': 'dict3_value3'},
{'key1': 'dict4_value1', 'key2': 'dict4_value2', 'key3': 'dict4_value3'},
{'key1': 'dict5_value1', 'key2': 'dict5_value2', 'key3': 'dict5_value3'}]
getting the value for 'key3' for the second list item is like:
dict_list[1]['key3']
dict2_value3
and also the code below returns items 2:4 from the list:
dict_list[1:3]
What if I want to get values for 'key3' for multiple items from the list. like
dict_list[1:3]['key3']
something similar to what we do in MATLAB.
>>> [x.get('key3') for x in dict_list[1:3]]
['dict2_value3', 'dict3_value3']
[dict_list[i]['key3'] for i in xrange(1,3)]
OR
[operator.itemgetter('key3')(dict_list[i]) for i in range(1,3)]
OR
map(operator.itemgetter('key3'), itertools.islice(dict_list, 1,3))
[x['key3'] for x in dict_list[1:3]]