This question already has answers here:
Splitting a semicolon-separated string to a dictionary, in Python
(6 answers)
Closed 5 years ago.
Hy i have a list of strings which look like:
atr = ['ID=cbs7435_mt', 'Name=cbs7435_mt', 'Dbxref=taxon:981350', 'Note=Pichia pastoris CBS 7435 mitochondrion%2C complete replicon sequence.', 'date=27-FEB-2015', 'mol_type=genomic DNA', 'organelle=mitochondrion', 'organism=Komagataella pastoris CBS 7435', 'strain=CBS 7435']
Now i want to create a dictionary which should look like:
my_dict = {'ID': 'cbs7435_mt', 'Name':'cbs7435_mt', ...}
Do someone has any advice how i could manage this?
Thanks already!
Simply split it with = and use dict()
my_dict = dict(i.split('=') for i in atr)
Use split() method of string to get Key and value for dictionary item.
Use for loop to iterate on given list input.
Demo:
>>> atr = ['ID=cbs7435_mt', 'Name=cbs7435_mt', 'Dbxref=taxon:981350']>>> result_dict = {}
>>> for item in atr:
... key, value = item.split("=")
... result_dict[key] = value
...
>>> result_dict
{'Dbxref': 'taxon:981350', 'ID': 'cbs7435_mt', 'Name': 'cbs7435_mt'}
>>>
Related
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 3 years ago.
I want to convert strings into blank list objects, which can then be updated/appended. How do I do this / can it even be done?
Imagine I have a string, 'blah'. I want to change this string, so that 'blah' becomes the object name of a blank list. In other words:
'blah'
def some_function('blah'):
...
...
return(blah)
some_function(blah)
OUTPUT: blah = []
I know that if I pass
list('blah')
this returns
['b','l','a','h']
But instead I want the opposite, where
list('blah')
returns
blah = []
Moving on from the comments, a more logical way out could be to use a dict:
d = {} # empty dict
s = 'blah' # str
d[s] = [] # empty list with the name of the str, blah = []
d[s].append("hello there!") # appending to `blah`
print(d[s])
You can't in any meaningful way. I'd suggest heeding #Mark Tolonen's advice and using a dictionary like so:
dictionary = {}
dictionary['blah'] = []
If you'd now like to add to 'blah', you can use append():
dictionary['blah'].append(x)
This question already has answers here:
Replacing multiple similar strings
(1 answer)
How to replace two things at once in a string?
(6 answers)
How to replace multiple substrings of a string?
(28 answers)
Closed 4 years ago.
I am trapped in a quite straight forward problem, but after some tweak, I simply cannot find an easy and efficient algorithm to do this.
So basically I have a string, which contains certain elements, for instance:
l = "test %1, %13, %14, %15"
And a map:
dict = {"%1": "%33", "%13": "%14", "%14", "%15", "%15": "%17"}
And I would like to do the following stuff:
for k in dict.keys():
l = l.replace(k, dict[k])
So what I am expecting is:
l = "test %33, %14, %15, %17"
But apparently this is not feasible, since there are some conflict between keys and values. So the above code would output:
l = "test %33, %17, %17, %17"
Sorry for such native problem, but how should I solve this and get my expected output? Note that the length of each key/value is not fixed, so I cannot do something like:
m_idx = l_copy.find(key)
l = l[:m_idx] + dict[key] + l[m_idx+len(key):]
Because the length is not fixed, the above code is still buggy.
Am I clear on this? Any suggestion would be appreciated very much!
======= update
So all keys follow this pattern of %[0-9]+.
You can use re.sub with a lambda:
import re
l = "test %1, %13, %14, %15"
_dict = {"%1": "%33", "%13": "%14", "%14":"%15", "%15": "%17"}
new_l = re.sub('%\d+', lambda x:_dict[x.group()], l)
Output:
'test %33, %14, %15, %17'
You can use dict.get to prevent a KeyError by providing a default value should the key not be present in _dict:
new_l = re.sub('%\d+', lambda x:_dict.get(x.group(), x.group()), l)
This question already has answers here:
Get keys from template
(7 answers)
Closed 5 years ago.
I have a prepared string, e.g. my_string = 'My name is {name}.'
and I have dictionary of kwargs, such as:
format_kwargs = {
'name': 'John',
...
}
So that I can format the string in this manner: my_string.format(**format_kwargs)
That is all good. The problem is that I want to determine what keys are in the string, so that I do not calculate the kwargs needlessly. That is, I have a set of keywords used in these strings by default, but not all of them are used in all strings. They are basically regular messages shown to user, such as '{name}, you account was successfully created!'.
I want to do something like:
format_kwargs = {}
if 'name' in <my_string.keys>:
format_kwargs['name'] = self.get_user().name
if '...' in <my_string.keys>:
format_kwargs['...'] = some_method_...()
my_string.format(**format_kwargs)
How do I retrieve the keys?
EDIT:
a simple if 'name' in my_string does not work because that would also match something like {parent_name} or 'The name change was not successful.'
Use string.Formatter
from string import Formatter
s = 'Hello {name}. Are you {debil_status}'
keys = [i[1] for i in Formatter().parse(s)]
print keys
>>> ['name', 'debil_status']
This question already has answers here:
python: read json and loop dictionary
(2 answers)
Closed 6 years ago.
I have a piece of json which was converted to a dict using the json function.
From this:
{
"imageIds": [
{
"imageTag": "1.2",
"imageDigest": "sha256:8b67b1691b29e27a5ccbd6fea5c97c951a025ccd45b26d4c24567ca3c4c0f13b"
},
{
"imageTag": "1.0",
"imageDigest": "sha256:aa52a12bd6e516659452af5b9ed0fad8659f9e0cea6a986c6bfe02af388df189"
}
]
}
To this:
>>> print data
{u'imageIds': [{u'imageTag': u'1.2', u'imageDigest': u'sha256:8b67b1691b29e27a5ccbd6fea5c97c951a025ccd45b26d4c24567ca3c4c0f13b'}, {u'imageTag': u'1.0', u'imageDigest': u'sha256:aa52a12bd6e516659452af5b9ed0fad8659f9e0cea6a986c6bfe02af388df189'}]}
In this example the number of keys (imageIds) is fixed but there could be any amount of imageTags under imageIds.
What I'm trying to do is loop through the 'imageTag' elements to read the tag number and perform an operation. If i wanted to loop through the key it seems straightforward with something simple like:
for key in data:
print key, 'corresponds to', data[key]
However I'm uncertain on how I loop through the items under the key.
What I want to achieve is to print out:
1.2
1.0
Iterate over inner dict the same way you do for the outer one:
for key, value in data.iteritems():
#now value can be a dictionary as well
#for innerkey, innervalues in value[0].iteritems():
# print innerkey, innervalues
#in order to only print the elements that have imageTag as the key, simply do:
print value[0]['imageTag']
This question already has answers here:
Automatically add key to Python dict
(3 answers)
Closed 7 years ago.
Suppose I create a dict like so:
foods = {}
And I eventually want to mutate some value of a nested dict within foods that doesn't yet exist:
foods['fruit']['apples'] = ['Granny Smith']
Is there a nice way to accomplish this insertion without checking the whole way:
if 'fruit' not in foods:
foods['fruit'] = {}
if 'apples' not in foods['fruit']:
foods['fruit']['apples'] = []
foods['fruit']['apples'].append('Granny Smith')
I guess I'm looking for a way to dynamically hash into nested dicts without explicitly instantiating them along the way.
I love the Python standard library. You want to use collections.defaultdict.
In this case, you want to nest them, so that foods is a defaultdict that, on the requested item not existing, generates a defaultdict that, on the requested item not existing, generates a list. Sounds complicated, but in the end, the result is not:
>>> from collections import defaultdict
>>> foods = defaultdict(lambda: defaultdict(list))
>>> foods['fruit']['apples'].append('Granny Smith')
>>> print(foods['fruit']['apples'])
['Granny Smith']
Your code:
if 'fruit' not in foods:
foods['fruit'] = {}
if 'apples' not in foods['fruit']:
foods['fruit']['apples'] = []
foods['fruit']['apples'].append('Granny Smith')
would be written as:
foods.setdefault('fruit', {}).setdefault('apples', []).append('Granny Smith')
Using setdefault(key[, default]).