remove unnecessary comma from python dict - python

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()))

Related

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('-', '')

Concatenate values in python dictionary

I have a python dictionary and I'd like to concatenate the values of value[0] and a list in value [1]
so
dict={ 'Key1':['MASTER',['_A','_B','_C']]}
and expected output is of calling Key1 is
[['MASTER_A','MASTER_B','MASTER_C']]
Use a nested comprehension:
d = {'Key1':['MASTER',['_A','_B','_C']]}
result_dict = {k: [v[0] + l for l in v[1]] for k,v in d.items()}
For example:
>>> result_dict = {k: [v[0] + l for l in v[1]] for k,v in d.items()}
>>> result_dict
{'Key1': ['MASTER_A', 'MASTER_B', 'MASTER_C']}
Try this :
d = {'Key1':['MASTER',['_A','_B','_C']]}
out = [d['Key1'][0]+i for i in d['Key1'][1]]
Output :
['MASTER_A', 'MASTER_B', 'MASTER_C']
To assign it to the key, do :
d['Key1'] = out

Getting a specific value of a key in a dictionary?

I have a dictionary like this:
d = {'k1':[0.2,0.65,0.23], 'k2':[0.32,1.2,3.3], 'k3':[1.8,0.6,0.4], ...}
So, I want to get a list of the key and the second value of each key in a list. I have tried this code:
names = list(d.keys())
values = list(d.values())
The first line is correct and gives me the list of all keys, but the second line provides all the values, which is not what I needed. So I need only the second or the third value of each key. Any suggestions?
Iterate over the dict and get the v[1] for each key, in a new dict:
d = {'k1':[0.2,0.65,0.23], 'k2':[0.32,1.2,3.3], 'k3':[1.8,0.6,0.4]}
print({k:v[1] for k,v in d.items()})
OUTPUT:
{'k1': 0.65, 'k2': 1.2, 'k3': 0.6}
try:
mylist = [(k, v[1]) for k, v in d.items()]
{k:v[1] for k,v in d.items()}
Create a new dict with the second value from the list-value of the original dict using a dictionary comprehension.
This will help you:
names = list(d.keys())
values = [v[1] for v in d.values()]
This iterate key and values per key
for k,v in d.items():
print("Key: %s" %k)
print("Values: %s" %v)
print("-"*8)
>>> import numpy as np
>>> d = {'k1':[0.2,0.65,0.23], 'k2':[0.32,1.2,3.3], 'k3':[1.8,0.6,0.4]}
>>> np.array(list(d.values()))[:,1]
Output:
array([0.65, 1.2 , 0.6 ])
d = {k1:[0.2,0.65,0.23], k2:[0.32,1.2,3.3], k3:[1.8,0.6,0.4], ...}
for fetching only 2nd element from the values, Below code will print only 2nd elements of each key
example - [v[1] for k,v in d.iteritems()]
prints [0.65,1.2,0.6]
for fetching key:value
{k:v[1] for k,v in d.iteritems()}
prints {'k1':0.65,'k2':1.2,'k3':0.6}
for fetching 2nd and 3rd element both , something like this can be done
{k:[v[1],v[2]] for k,v in d.iteritems()}

How to convert a dict to string?

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() )

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