How to convert a dict to string? - python

Assume I have a dict:
{
'a':'vala',
'b':'valb',
'c':'valc'
}
I want to convert this to a string:
"a='vala' , b='valb' c='valc'"
What is the best way to get there? I want to do something like:
mystring = ""
for key in testdict:
mystring += "{}='{}'".format(key, testdict[key]).join(',')

You can use str.join with a generator expression for this. Note that a dictionary doesn't have any order, so the items will be arbitrarily ordered:
>>> dct = {'a':'vala', 'b':'valb'}
>>> ','.join('{}={!r}'.format(k, v) for k, v in dct.items())
"a='vala',b='valb'"
If you want quotes around the values regardless of their type then replace {!r} with '{}'. An example showing the difference:
>>> dct = {'a': 1, 'b': '2'}
>>> ','.join('{}={!r}'.format(k, v) for k, v in dct.items())
"a=1,b='2'"
>>> ','.join("{}='{}'".format(k, v) for k, v in dct.items())
"a='1',b='2'"

Close! .join is used to join together items in an iterable by a character, so you needed to append those items to a list, then join them together by a comma at the end like so:
testdict ={
'a':'vala',
'b':'valb'
}
mystring = []
for key in testdict:
mystring.append("{}='{}'".format(key, testdict[key]))
print ','.join(mystring)

Well, just if you want to have a sorted result:
d={'a':'vala', 'b':'valb', 'c':'valc'}
st = ", ".join("{}='{}'".format(k, v) for k, v in sorted(d.items()))
print(st)
Result
a='vala', b='valb', c='valc'

" , ".join( "%s='%s'"%(key,val) for key,val in mydict.items() )

Related

Extract differences of values of 2 given dictionaries - values are tuples of strings

I have two dictionaries as follows, I need to extract which strings in the tuple values are in one dictionary but not in other:
dict_a = {"s": ("mmmm", "iiiii", "p11"), "yyzz": ("oo", "i9")}
dict_b = {"s": ("mmmm",), "h": ("pp",), "g": ("rr",)}
The desired output:
{"s": ("iiiii", "p11"), "yyzz": ("oo", "i9")}
The order of the strings in the output doesn't matter.
One way that I tried to solve, but it doesn't produce the expected result:
>>> [item for item in dict_a.values() if item not in dict_b.values()]
[('mmmm', 'iiiii', 'p11'), ('oo', 'i9')]
If order doesn't matter, convert your dictionary values to sets, and subtract these:
{k: set(v) - set(dict_b.get(k, ())) for k, v in dict_a.items()}
The above takes all key-value pairs from dict_a, and for each such pair, outputs a new dictionary with those keys and a new value that's the set difference between the original value and the corresponding value from dict_b, if there is one:
>>> dict_a = {"s": ("mmmm", "iiiii", "p11"), "yyzz": ("oo", "i9")}
>>> dict_b = {"s": ("mmmm",), "h": ("pp",), "g": ("rr",)}
>>> {k: set(v) - set(dict_b.get(k, ())) for k, v in dict_a.items()}
{'s': {'p11', 'iiiii'}, 'yyzz': {'oo', 'i9'}}
The output will have sets, but these can be converted back to tuples if necessary:
{k: tuple(set(v) - set(dict_b.get(k, ()))) for k, v in dict_a.items()}
The dict_b.get(k, ()) call ensures there is always a tuple to give to set().
If you use the set.difference() method you don't even need to turn the dict_b value to a set:
{k: tuple(set(v).difference(dict_b.get(k, ()))) for k, v in dict_a.items()}
Demo of the latter two options:
>>> {k: tuple(set(v) - set(dict_b.get(k, ()))) for k, v in dict_a.items()}
{'s': ('p11', 'iiiii'), 'yyzz': ('oo', 'i9')}
>>> {k: tuple(set(v).difference(dict_b.get(k, ()))) for k, v in dict_a.items()}
{'s': ('p11', 'iiiii'), 'yyzz': ('oo', 'i9')}
{k: [v for v in vs if v not in dict_b.get(k, [])] for k,vs in dict_a.items()}
if you want to use tuples (or sets - just replace the cast)
{k: tuple(v for v in vs if v not in dict_b.get(k, [])) for k,vs in dict_a.items()}
Try this (see comments for explanations):
>>> out = {} # Initialise output dictionary
>>> for k, v in dict_a.items(): # Iterate through items of dict_a
... if k not in dict_b: # Check if the key is not in dict_b
... out[k] = v # If it isn't, add to out
... else: # Otherwise
... out[k] = tuple(set(v) - set(dict_b[k])) # Subtract sets to find the difference
...
>>> out
{'s': ('iiiii', 'p11'), 'yyzz': ('oo', 'i9')}
This can then be simplified using a dictionary comprehension:
>>> out = {k: tuple(set(v) - set(dict_b.get(k, ()))) for k, v in dict_a.items()}
>>> out
{'s': ('iiiii', 'p11'), 'yyzz': ('oo', 'i9')}
See this solution :
First iterate through all keys in dict_a
Check if the key is present or not in dict_b
Now, if present: take the tuples and iterate through dict_a's tuple(as per your question). now check weather that element is present or not in dict_b's tuple. If it is present just leave it. If it is not just add that element in tup_res.
Now after the for loop, add that key and tup value in the dict_res.
if the key is not present in dict_b simply add it in dict_res.
dict_a = {"s":("mmmm","iiiii","p11"), "yyzz":("oo","i9")}
dict_b = {"s":("mmmm"),"h":("pp",),"g":("rr",)}
dict_res = {}
for key in dict_a:
if key in dict_b:
tup_a = dict_a[key]
tup_b = dict_b[key]
tup_res = ()
for tup_ele in tup_a:
if tup_ele in tup_b:
pass
else:
tup_res = tup_res + (tup_ele,)
dict_res[key] = tup_res;
else:
dict_res[key] = dict_a[key];
print(dict_res)
It is giving correct output :)

Read a string in dictionary values and replace a specific character

I have a dict in which each value is a string. In some values, this string has "-" that I would like to remove. I have been told that it is not possible to replace the values of a dict. Is that right?
mydict
'GCA_000010565.1_genomic Ribosomal_L10:': '-TRAEKEAIIQELKEKFKEARVAVLADYRGLNV-------AEATRLRRRLREAGCEFKVAKNTLTGLAARQAGLE-----GLDPYLEGPIAIAFG-VDPVAPAKVLSDF--',
I would wish something like
mydict
'GCA_000010565.1_genomic Ribosomal_L10:': 'TRAEKEAIIQELKEKFKEARVAVLADYRGLNVAEATRLRRRLREAGCEFKVAKNTLTGLAARQAGLEGLDPYLEGPIAIAFGVDPVAPAKVLSDF',
Absolutly you can, just iterate over the mappings key/value, and change the associated value by the processed one
d = {'superkey': "foo--bar", 'superkey2': "--foo--bar",
'GCA_000010565.1_genomic Ribosomal_L10:': '-TRAEKEAIIQELKEKFKEARVAVLADYRGLNV-------AEATRLRRRLREAGCEFKVAKNTLTGLAARQAGLE-----GLDPYLEGPIAIAFG-VDPVAPAKVLSDF--', }
# LOOP version
for k, v in d.items():
d[k] = v.replace("-", "")
# DICT COMPREHENSION version
d = {k: v.replace("-", "") for k, v in d.items()}
print(d) # {'superkey': 'foobar', 'superkey2': 'foobar',
'GCA_000010565.1_genomic Ribosomal_L10:': 'TRAEKEAIIQELKEKFKEARVAVLADYRGLNVAEATRLRRRLREAGCEFKVAKNTLTGLAARQAGLEGLDPYLEGPIAIAFGVDPVAPAKVLSDF'}
Yes it is possible. You can simply use
mydict['GCA_000010565.1_genomic Ribosomal_L10:'] = mydict['GCA_000010565.1_genomic Ribosomal_L10:'].replace("-","")
No, you've been told BS. The solution:
for k in mydict:
mydict[k] = mydict[k].replace('-', '')

remove unnecessary comma from python dict

My dict is,
d= {'add1':'','add2':'address2','add3':'' }
I want to join all the values as a list of comma separated words.
if d is d= {'add1':'','add2':'address2','add3':'' }
then output would be address2
if d is d= {'add1':'address1','add2':'address2','add3':'' }
then output would be address1,address2
if d is d= {'add1':'address1','add2':'address2','add3':'address3' }
then output would be address1,address2,address3
if d is d= {'add1':'','add2':'','add3':'' }
then output would be '' (simply blank string)
What I have tried ?
",".join([d.get('add1',''), d.get('add2',''), d.get('add3','')])
but I am not getting output as I expected.
If you don't need to worry about order
','.join(value for value in d.itervalues() if value)
If your keys are always add1 etc, they will be easily sortable to ensure order
','.join(d[key] for key in sorted(d.keys()) if d[key])
You may simply join non-empty values:
','.join(v for v in d.itervalues() if v)
You have to filter out the empty stings first:
",".join([x for x in d.values() if x])
You can use list comprehension after getting d.values() and then str.join() -
','.join([v for v in d.values() if v])
Demo -
>>> d= {'add1':'','add2':'address2','add3':'' }
>>> ','.join([v for v in d.values() if v])
'address2'
>>> d= {'add1':'address1','add2':'address2','add3':'' }
>>> ','.join([v for v in d.values() if v])
'address1,address2'
>>> d= {'add1':'','add2':'','add3':'' }
>>> ','.join([v for v in d.values() if v])
''
>>> d= {'add1':'address1','add2':'address2','add3':'address2' }
>>> ','.join([v for v in d.values() if v])
'address1,address2,address2'
Use dict.values() method and filter function:
','.join(filter(None, d.values()))

Python : Match a dictionary value with another dictionary key

I have two dictionaries created this way :
tr = defaultdict(list)
tr = { 'critic' : '2_critic',
'major' : '3_major',
'all' : ['2_critic','3_major']
}
And the second one :
scnd_dict = defaultdict(list)
And contains values like this :
scnd_dict = {'severity': ['all']}
I want to have a third dict that will contain the key of scnd_dict and its corresponding value from tr.
This way, I will have :
third_dict = {'severity' : ['2_critic','3_major']}
I tried this, but it didn't work :
for (k,v) in scnd_dict.iteritems() :
if v in tr:
third_dict[k].append(tr[v])
Any help would be appreciated. Thanks.
Well...
from collections import defaultdict
tr = {'critic' : '2_critic',
'major' : '3_major',
'all' : ['2_critic','3_major']}
scnd_dict = {'severity': ['all']}
third_dict = {}
for k, v in scnd_dict.iteritems():
vals = []
if isinstance(v, list):
for i in v:
vals.append(tr.get(i))
else:
vals.append(tr.get(v))
if not vals:
continue
third_dict[k] = vals
print third_dict
Results:
>>>
{'severity': [['2_critic', '3_major']]}
Will do what you want. But I question the logic of using defaultdicts here, or of have your index part of a list...
If you use non-lists for scnd_dict then you can do the whole thing much easier. Assuming scnd_dict looks like this: scnd_dict = {'severity': 'all'}:
d = dict((k, tr.get(v)) for k, v in scnd_dict.items())
# {'severity': ['2_critic', '3_major']}
Your problem is that v is a list, not an item of a list. So, the if v in tr: will be false. Change your code so that you iterate over the items in v
third_dict = {k: [t for m in ks for t in tr[m]] for k,ks in scnd_dict.iteritems()}
The second dict's value is list, not str, so the code blow will work
for (k, v) in send_dict.iteritems():
if v[0] in tr.keys():
third_dict[k] = tr[v[0]]
The problem is that the third dictionary does not knows that the values is a list
for k in scnd_dict:
for v in scnd_dict[k]:
print v
for k2 in tr:
if v==k2:
if k not in third_dict:
third_dict[k]=tr[k2]
else:
third_dict[k]+=tr[k2]
third_dict = {k: tr[v[0]] for k, v in scnd_dict.iteritems() if v[0] in tr}
This
tr = defaultdict(list)
is a waste of time if you are just rebinding tr on the next line. Likewise for scnd_dict.
It's a better idea to make all the values of tr lists - even if they only have one item. It will mean less special cases to worry about later on.

Deleting from dict if found in new list in Python

Say I have a dictionary with whatever number of values.
And then I create a list.
If any of the values of the list are found in the dictionary, regardless of whether or not it is a key or an index how do I delete the full value?
E.g:
dictionary = {1:3,4:5}
list = [1]
...
dictionary = {4:5}
How do I do this without creating a new dictionary?
for key, value in list(dic.items()):
if key in lst or value in lst:
del dic[key]
No need to create a separate list or dictionary.
I interpreted "whether or not it is a key or an index" to mean "whether or not it is a key or a value [in the dictionary]"
it's a bit complicated because of your "values" requirement:
>>> dic = {1: 3, 4: 5}
>>> ls = set([1])
>>> dels = []
>>> for k, v in dic.items():
if k in ls or v in ls:
dels.append(k)
>>> for i in dels:
del dic[i]
>>> dic
{4: 5}
A one liner to do this would be :
[dictionary.pop(x) for x in list if x in dictionary.keys()]
dictionary = {1:3,4:5}
list = [1]
for key in list:
if key in dictionary:
del dictionary[key]
>>> dictionary = {1:3,4:5}
>>> list = [1]
>>> for x in list:
... if x in dictionary:
... del(dictionary[x])
...
>>> dictionary
{4: 5}
def remKeys(dictionary, list):
for i in list:
if i in dictionary.keys():
dictionary.pop(i)
return dictionary
I would do something like:
for i in list:
if dictionary.has_key(i):
del dictionary[i]
But I am sure there are better ways.
A few more testcases to define how I interpret your question:
#!/usr/bin/env python
def test(beforedic,afterdic,removelist):
d = beforedic
l = removelist
for i in l:
for (k,v) in list(d.items()):
if k == i or v == i:
del d[k]
assert d == afterdic,"d is "+str(d)
test({1:3,4:5},{4:5},[1])
test({1:3,4:5},{4:5},[3])
test({1:3,4:5},{1:3,4:5},[9])
test({1:3,4:5},{4:5},[1,3])
If the dictionary is small enough, it's easier to just make a new one. Removing all items whose key is in the set s from the dictionary d:
d = dict((k, v) for (k, v) in d.items() if not k in s)
Removing all items whose key or value is in the set s from the dictionary d:
d = dict((k, v) for (k, v) in d.items() if not k in s and not v in s)

Categories