when I try to dump a python dictionary to yaml file, I get results with quotes both keys and values.
For example I create a python dictonary:
d = { 'a': '1', 'b': '2' }
with open(attributes_file, "w") as fw:
yaml.dump(dict_attributes, fw)
I get this output:
'a': '1'
'b': '2'
How to remove quotes?
You must convert values to int like this
d2 = {k: int(v) for k,v in d.items()}
and save d2 dict.
Related
I have dictionary that looks like this: 'a': 'NPRO,206', 'b': 'PREP,131', 'c': 'PRCL,120', 'd': 'NPRO,66'etc.
I want to create output that will look like this:NPRO:'a,d', PRCL:'c', PREP:'b'
First of all you have to take all the values like NPRO, PRCL, note that they appear more than once. So, If you won't remove the duplicate ones you can end up adding same value to a key twice.
You can use set(), set is just like sets in mathematics. You can't have a duplicate value. Even if i put 1,2,3,3,1 in the set it finally it would look like 1,2,3
Do something like this:
d = {'a': 'NPRO,206', 'b': 'PREP,131', 'c': 'PRCL,120', 'd': 'NPRO,66'}
new_dict = {}
for k in set(val.split(',')[0] for val in d.values()):
for key, value in d.items():
if k in value:
try:
new_dict[k].append(key)
except KeyError as err:
new_dict[k] = [key]
print(new_dict)
This should print this:
{'NPRO': ['a', 'd'], 'PRCL': ['c'], 'PREP': ['b']}
Note:
This code can be improved but as you said you are new, I have kept things simple.
d = {'A': ['A11117',
'33465'
'17160144',
'A11-33465',
'3040',
'A11-33465 W1',
'nor'], 'B': ['maD', 'vern', 'first', 'A2lRights']}
I have a dictionary d and I would like to sort the values based on length of characters. For instance, for key A the value A11-33465 W1 would be first because it contains 12 characters followed by 'A11-33465' because it contains 9 characters etc. I would like this output:
d = {'A': ['A11-33465 W1',
' A11-33465',
'17160144',
'A11117',
'33465',
'3040',
'nor'],
'B': ['A2lRights',
'first',
'vern',
'maD']}
(I understand that dictionaries are not able to be sorted but I have examples below that didn't work for me but the answer contains a dictionary that was sorted)
I have tried the following
python sorting dictionary by length of values
print(' '.join(sorted(d, key=lambda k: len(d[k]), reverse=True)))
Sort a dictionary by length of the value
sorted_items = sorted(d.items(), key = lambda item : len(item[1]))
newd = dict(sorted_items[-2:])
How do I sort a dictionary by value?
import operator
sorted_x = sorted(d.items(), key=operator.itemgetter(1))
But they both do not give me what I am looking for.
How do I get my desired output?
You are not sorting the dict, you are sorting the lists inside it. The simplest will be a loop that sorts the lists in-place:
for k, lst in d.items():
lst.sort(key=len, reverse=True)
This will turn d into:
{'A': ['3346517160144', 'A11-33465 W1', 'A11-33465', 'A11117', '3040', 'nor'],
'B': ['A2lRights', 'first', 'vern', 'maD']}
If you want to keep the original data intact, use a comprehension like:
sorted_d = {k: sorted(lst, key=len, reverse=True) for k, lst in d.items()}
I have a input string input_str = 'a=1;b=2;c' and I want to split it into dictionary as {'a':1, 'b':2, 'c': '.'}
input_str = 'a=1;b=2;c'
default = '.'
output = dict(s.split('=') if '=' in s else {s ,default} for s in input_str.split(';'))
print(output)
{'a': '1', 'b': '2', '.': 'c'}
# Output I want:
{'a': '1', 'b': '2', 'c': '.'}
Following code works.But I was looking for a one liner with dict comprehension.
my_result = {}
input_str = 'a=1;b=2;c'
for s in input_str.split(';'):
if '=' in s:
key, val = s.split('=')
my_result[key] = val
else:
my_result[s] = '.'
I noticed that else condition in above code {s ,default} is treated as set. How to convert it into dictionary.
As you noted, {s, default} defines a set, and the order of sets is undefined.
All you need to do to remedy this is to use a list instead.
dict(s.split('=', 1) if '=' in s else [s, default] for s in input_str.split(';'))
Note, this is unlikely to be very useful in real-life unless you have very restricted requirements. What happens if you want to include a value that contains a ';' character?
By changing the first split() call to have , 1, this means that the value will only ever be split once, no matter how many '=' characters there are.
For example, trying to parse an input of: a=bad=value;b=2 would raise a ValueError.
I have two python dicts:
payload = {"key1":{"a":"1"},"key2":{"b":"2","c":"3"}}
and
data = {"1":"John","2":"Jacob"}
I would like my output to be:
{"key1":{"a":"John"},"key2":{"b":"Jacob","c":""}}
Any method that I try correctly prints the values, but does not update the output dictionary.
You can do something like this using dict comprehension :
payload = {"key1":{"a":"1"},"key2":{"b":"2","c":"3"}}
data = {"1":"John","2":"Jacob"}
final = {k: {i:data[j] if j in data.keys() else "" for i, j in payload[k].items()} for k in payload}
print(final)
Output:
{'key2': {'b': 'Jacob', 'c': ''}, 'key1': {'a': 'John'}}
There is no single method for this I am aware of, but you can use:
for k, v in payload.viewitems():
payload[k] = {}
for kv, vv in v.viewitems():
payload[k][kv] = data.get(vv, "")
if you then inspect payload it has the contents you are after:
{'key2': {'c': '', 'b': 'Jacob'}, 'key1': {'a': 'John'}}
This is my INPUT:
dic1 = {'a':'USA', 'b':'Canada', 'c':'France'}
dic2 = {'c':'Italy', 'd':'Norway', 'e':'Denmark'}
dic3 = {'e':'Finland', 'f':'Japan', 'g':'Germany’}
I want output something like below:
{'g': 'Germany', 'e': [‘Denmark’,’Finland'], 'd': 'Norway', 'c': ['Italy’,'France', 'f': 'Japan', 'b': 'Canada', 'a': 'USA'}
That is programing - you think the steps you need to get to your desired results, and write code to perform these steps, one at a time.
A funciton like this can do it:
def merge_dicts(*args):
merged = {}
for dct in args:
for key, value in dct.items():
if key not in merged:
merged[key] = []
merged[key].append(value)
return merged