Convert a string to list of dictionaries
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
I have a string as below
gmr='rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
If you see clearly its kind of 2 dictionaries
rule:unique,attribute:geo,name:unq1
and
rule:sum,attribute:sales,name:sum_sales
I want to convert them to as below
[
{'rule': 'sum', 'attribute': 'sales', 'name': 'sum_sales'},
{'rule': 'unique', 'attribute': 'geo', 'name': 'uniq1'}
]
Kindly help
I tried
gmr='rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
dlist=
at_rule_gm=(x.split(':') for x in gmr.split(','))
dict(at_rule_gm)
but here I get only the last dictionary.
python python-3.x string list dictionary
add a comment |
I have a string as below
gmr='rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
If you see clearly its kind of 2 dictionaries
rule:unique,attribute:geo,name:unq1
and
rule:sum,attribute:sales,name:sum_sales
I want to convert them to as below
[
{'rule': 'sum', 'attribute': 'sales', 'name': 'sum_sales'},
{'rule': 'unique', 'attribute': 'geo', 'name': 'uniq1'}
]
Kindly help
I tried
gmr='rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
dlist=
at_rule_gm=(x.split(':') for x in gmr.split(','))
dict(at_rule_gm)
but here I get only the last dictionary.
python python-3.x string list dictionary
add a comment |
I have a string as below
gmr='rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
If you see clearly its kind of 2 dictionaries
rule:unique,attribute:geo,name:unq1
and
rule:sum,attribute:sales,name:sum_sales
I want to convert them to as below
[
{'rule': 'sum', 'attribute': 'sales', 'name': 'sum_sales'},
{'rule': 'unique', 'attribute': 'geo', 'name': 'uniq1'}
]
Kindly help
I tried
gmr='rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
dlist=
at_rule_gm=(x.split(':') for x in gmr.split(','))
dict(at_rule_gm)
but here I get only the last dictionary.
python python-3.x string list dictionary
I have a string as below
gmr='rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
If you see clearly its kind of 2 dictionaries
rule:unique,attribute:geo,name:unq1
and
rule:sum,attribute:sales,name:sum_sales
I want to convert them to as below
[
{'rule': 'sum', 'attribute': 'sales', 'name': 'sum_sales'},
{'rule': 'unique', 'attribute': 'geo', 'name': 'uniq1'}
]
Kindly help
I tried
gmr='rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
dlist=
at_rule_gm=(x.split(':') for x in gmr.split(','))
dict(at_rule_gm)
but here I get only the last dictionary.
python python-3.x string list dictionary
python python-3.x string list dictionary
edited Jan 3 at 9:13


jpp
103k2166116
103k2166116
asked Jan 3 at 8:43
Kumar PKumar P
526
526
add a comment |
add a comment |
3 Answers
3
active
oldest
votes
Start with sample of OP:
>>> gmr='rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
Make an empty list first.
>>> dlist = [ ]
Loop with entry
over list, yielded by gmr.split(',')
,
Store entry.split(':')
into pair
,
Check whether first value in pair
(the key) is 'rule'
If so, append a new empty dictionary to dlist
Store pair into last entry of dlist
:
>>> for entry in gmr.split(','):
pair = entry.split(':')
if pair[0] == 'rule':
dlist.append({ })
dlist[-1][pair[0]] = pair[1]
Print result:
>>> print(dlist)
[{'name': 'unq1', 'attribute': 'geo', 'rule': 'unique'},
{'name': 'sum_sales', 'attribute': 'sales', 'rule': 'sum'}]
Looks like what OP intended to get.
add a comment |
gmr='rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
split_str = gmr.split(',')
dlist =
for num in range(0, len(split_str),3):
temp_dict = {}
temp1 = split_str[num]
temp2 = split_str[num+1]
temp3 = split_str[num+2]
key,value = temp1.split(':')
temp_dict.update({key:value})
key,value = temp2.split(':')
temp_dict.update({key:value})
key,value = temp3.split(':')
temp_dict.update({key:value})
dlist.append(temp_dict)
Please add some context to your answer.
– Tobias Wilfert
Jan 3 at 9:17
add a comment |
dict
always gives a single dictionary, not a list
of dictionaries. For the latter, you can use a list comprehension after first splitting by 'rule:'
:
gmr = 'rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
items = (f'rule:{x}' for x in filter(None, gmr.split('rule:')))
res = [dict(x.split(':') for x in item.split(',') if x) for item in items]
print(res)
# [{'attribute': 'geo', 'name': 'unq1', 'rule': 'unique'},
# {'attribute': 'sales', 'name': 'sum_sales', 'rule': 'sum'}]
TypeError Traceback (most recent call last) <ipython-input-367-dcc148ac40d3> in <module>() 1 items = (f'rule:{x}' for x in filter(None, gmr.split('rule:'))) ----> 2 res = [dict(x.split(':') for x in item.split(',') if x) for item in items] <ipython-input-367-dcc148ac40d3> in <listcomp>(.0) 1 items = (f'rule:{x}' for x in filter(None, gmr.split('rule:'))) ----> 2 res = [dict(x.split(':') for x in item.split(',') if x) for item in items] TypeError: 'dict' object is not callable
– Kumar P
Jan 3 at 9:29
@KumarP, Can't replicate, the example I give works fine and is identical to your input.
– jpp
Jan 3 at 9:30
@KumarP, It's probably because you've defined a variabledict
earlier. Don't do this. Used_
,dict_
,dct
, or something else.
– jpp
Jan 3 at 9:30
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54018874%2fconvert-a-string-to-list-of-dictionaries%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
Start with sample of OP:
>>> gmr='rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
Make an empty list first.
>>> dlist = [ ]
Loop with entry
over list, yielded by gmr.split(',')
,
Store entry.split(':')
into pair
,
Check whether first value in pair
(the key) is 'rule'
If so, append a new empty dictionary to dlist
Store pair into last entry of dlist
:
>>> for entry in gmr.split(','):
pair = entry.split(':')
if pair[0] == 'rule':
dlist.append({ })
dlist[-1][pair[0]] = pair[1]
Print result:
>>> print(dlist)
[{'name': 'unq1', 'attribute': 'geo', 'rule': 'unique'},
{'name': 'sum_sales', 'attribute': 'sales', 'rule': 'sum'}]
Looks like what OP intended to get.
add a comment |
Start with sample of OP:
>>> gmr='rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
Make an empty list first.
>>> dlist = [ ]
Loop with entry
over list, yielded by gmr.split(',')
,
Store entry.split(':')
into pair
,
Check whether first value in pair
(the key) is 'rule'
If so, append a new empty dictionary to dlist
Store pair into last entry of dlist
:
>>> for entry in gmr.split(','):
pair = entry.split(':')
if pair[0] == 'rule':
dlist.append({ })
dlist[-1][pair[0]] = pair[1]
Print result:
>>> print(dlist)
[{'name': 'unq1', 'attribute': 'geo', 'rule': 'unique'},
{'name': 'sum_sales', 'attribute': 'sales', 'rule': 'sum'}]
Looks like what OP intended to get.
add a comment |
Start with sample of OP:
>>> gmr='rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
Make an empty list first.
>>> dlist = [ ]
Loop with entry
over list, yielded by gmr.split(',')
,
Store entry.split(':')
into pair
,
Check whether first value in pair
(the key) is 'rule'
If so, append a new empty dictionary to dlist
Store pair into last entry of dlist
:
>>> for entry in gmr.split(','):
pair = entry.split(':')
if pair[0] == 'rule':
dlist.append({ })
dlist[-1][pair[0]] = pair[1]
Print result:
>>> print(dlist)
[{'name': 'unq1', 'attribute': 'geo', 'rule': 'unique'},
{'name': 'sum_sales', 'attribute': 'sales', 'rule': 'sum'}]
Looks like what OP intended to get.
Start with sample of OP:
>>> gmr='rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
Make an empty list first.
>>> dlist = [ ]
Loop with entry
over list, yielded by gmr.split(',')
,
Store entry.split(':')
into pair
,
Check whether first value in pair
(the key) is 'rule'
If so, append a new empty dictionary to dlist
Store pair into last entry of dlist
:
>>> for entry in gmr.split(','):
pair = entry.split(':')
if pair[0] == 'rule':
dlist.append({ })
dlist[-1][pair[0]] = pair[1]
Print result:
>>> print(dlist)
[{'name': 'unq1', 'attribute': 'geo', 'rule': 'unique'},
{'name': 'sum_sales', 'attribute': 'sales', 'rule': 'sum'}]
Looks like what OP intended to get.
answered Jan 3 at 9:12


ScheffScheff
8,30821426
8,30821426
add a comment |
add a comment |
gmr='rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
split_str = gmr.split(',')
dlist =
for num in range(0, len(split_str),3):
temp_dict = {}
temp1 = split_str[num]
temp2 = split_str[num+1]
temp3 = split_str[num+2]
key,value = temp1.split(':')
temp_dict.update({key:value})
key,value = temp2.split(':')
temp_dict.update({key:value})
key,value = temp3.split(':')
temp_dict.update({key:value})
dlist.append(temp_dict)
Please add some context to your answer.
– Tobias Wilfert
Jan 3 at 9:17
add a comment |
gmr='rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
split_str = gmr.split(',')
dlist =
for num in range(0, len(split_str),3):
temp_dict = {}
temp1 = split_str[num]
temp2 = split_str[num+1]
temp3 = split_str[num+2]
key,value = temp1.split(':')
temp_dict.update({key:value})
key,value = temp2.split(':')
temp_dict.update({key:value})
key,value = temp3.split(':')
temp_dict.update({key:value})
dlist.append(temp_dict)
Please add some context to your answer.
– Tobias Wilfert
Jan 3 at 9:17
add a comment |
gmr='rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
split_str = gmr.split(',')
dlist =
for num in range(0, len(split_str),3):
temp_dict = {}
temp1 = split_str[num]
temp2 = split_str[num+1]
temp3 = split_str[num+2]
key,value = temp1.split(':')
temp_dict.update({key:value})
key,value = temp2.split(':')
temp_dict.update({key:value})
key,value = temp3.split(':')
temp_dict.update({key:value})
dlist.append(temp_dict)
gmr='rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
split_str = gmr.split(',')
dlist =
for num in range(0, len(split_str),3):
temp_dict = {}
temp1 = split_str[num]
temp2 = split_str[num+1]
temp3 = split_str[num+2]
key,value = temp1.split(':')
temp_dict.update({key:value})
key,value = temp2.split(':')
temp_dict.update({key:value})
key,value = temp3.split(':')
temp_dict.update({key:value})
dlist.append(temp_dict)
answered Jan 3 at 9:11
Mathi VananMathi Vanan
112
112
Please add some context to your answer.
– Tobias Wilfert
Jan 3 at 9:17
add a comment |
Please add some context to your answer.
– Tobias Wilfert
Jan 3 at 9:17
Please add some context to your answer.
– Tobias Wilfert
Jan 3 at 9:17
Please add some context to your answer.
– Tobias Wilfert
Jan 3 at 9:17
add a comment |
dict
always gives a single dictionary, not a list
of dictionaries. For the latter, you can use a list comprehension after first splitting by 'rule:'
:
gmr = 'rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
items = (f'rule:{x}' for x in filter(None, gmr.split('rule:')))
res = [dict(x.split(':') for x in item.split(',') if x) for item in items]
print(res)
# [{'attribute': 'geo', 'name': 'unq1', 'rule': 'unique'},
# {'attribute': 'sales', 'name': 'sum_sales', 'rule': 'sum'}]
TypeError Traceback (most recent call last) <ipython-input-367-dcc148ac40d3> in <module>() 1 items = (f'rule:{x}' for x in filter(None, gmr.split('rule:'))) ----> 2 res = [dict(x.split(':') for x in item.split(',') if x) for item in items] <ipython-input-367-dcc148ac40d3> in <listcomp>(.0) 1 items = (f'rule:{x}' for x in filter(None, gmr.split('rule:'))) ----> 2 res = [dict(x.split(':') for x in item.split(',') if x) for item in items] TypeError: 'dict' object is not callable
– Kumar P
Jan 3 at 9:29
@KumarP, Can't replicate, the example I give works fine and is identical to your input.
– jpp
Jan 3 at 9:30
@KumarP, It's probably because you've defined a variabledict
earlier. Don't do this. Used_
,dict_
,dct
, or something else.
– jpp
Jan 3 at 9:30
add a comment |
dict
always gives a single dictionary, not a list
of dictionaries. For the latter, you can use a list comprehension after first splitting by 'rule:'
:
gmr = 'rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
items = (f'rule:{x}' for x in filter(None, gmr.split('rule:')))
res = [dict(x.split(':') for x in item.split(',') if x) for item in items]
print(res)
# [{'attribute': 'geo', 'name': 'unq1', 'rule': 'unique'},
# {'attribute': 'sales', 'name': 'sum_sales', 'rule': 'sum'}]
TypeError Traceback (most recent call last) <ipython-input-367-dcc148ac40d3> in <module>() 1 items = (f'rule:{x}' for x in filter(None, gmr.split('rule:'))) ----> 2 res = [dict(x.split(':') for x in item.split(',') if x) for item in items] <ipython-input-367-dcc148ac40d3> in <listcomp>(.0) 1 items = (f'rule:{x}' for x in filter(None, gmr.split('rule:'))) ----> 2 res = [dict(x.split(':') for x in item.split(',') if x) for item in items] TypeError: 'dict' object is not callable
– Kumar P
Jan 3 at 9:29
@KumarP, Can't replicate, the example I give works fine and is identical to your input.
– jpp
Jan 3 at 9:30
@KumarP, It's probably because you've defined a variabledict
earlier. Don't do this. Used_
,dict_
,dct
, or something else.
– jpp
Jan 3 at 9:30
add a comment |
dict
always gives a single dictionary, not a list
of dictionaries. For the latter, you can use a list comprehension after first splitting by 'rule:'
:
gmr = 'rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
items = (f'rule:{x}' for x in filter(None, gmr.split('rule:')))
res = [dict(x.split(':') for x in item.split(',') if x) for item in items]
print(res)
# [{'attribute': 'geo', 'name': 'unq1', 'rule': 'unique'},
# {'attribute': 'sales', 'name': 'sum_sales', 'rule': 'sum'}]
dict
always gives a single dictionary, not a list
of dictionaries. For the latter, you can use a list comprehension after first splitting by 'rule:'
:
gmr = 'rule:unique,attribute:geo,name:unq1,rule:sum,attribute:sales,name:sum_sales'
items = (f'rule:{x}' for x in filter(None, gmr.split('rule:')))
res = [dict(x.split(':') for x in item.split(',') if x) for item in items]
print(res)
# [{'attribute': 'geo', 'name': 'unq1', 'rule': 'unique'},
# {'attribute': 'sales', 'name': 'sum_sales', 'rule': 'sum'}]
answered Jan 3 at 9:12


jppjpp
103k2166116
103k2166116
TypeError Traceback (most recent call last) <ipython-input-367-dcc148ac40d3> in <module>() 1 items = (f'rule:{x}' for x in filter(None, gmr.split('rule:'))) ----> 2 res = [dict(x.split(':') for x in item.split(',') if x) for item in items] <ipython-input-367-dcc148ac40d3> in <listcomp>(.0) 1 items = (f'rule:{x}' for x in filter(None, gmr.split('rule:'))) ----> 2 res = [dict(x.split(':') for x in item.split(',') if x) for item in items] TypeError: 'dict' object is not callable
– Kumar P
Jan 3 at 9:29
@KumarP, Can't replicate, the example I give works fine and is identical to your input.
– jpp
Jan 3 at 9:30
@KumarP, It's probably because you've defined a variabledict
earlier. Don't do this. Used_
,dict_
,dct
, or something else.
– jpp
Jan 3 at 9:30
add a comment |
TypeError Traceback (most recent call last) <ipython-input-367-dcc148ac40d3> in <module>() 1 items = (f'rule:{x}' for x in filter(None, gmr.split('rule:'))) ----> 2 res = [dict(x.split(':') for x in item.split(',') if x) for item in items] <ipython-input-367-dcc148ac40d3> in <listcomp>(.0) 1 items = (f'rule:{x}' for x in filter(None, gmr.split('rule:'))) ----> 2 res = [dict(x.split(':') for x in item.split(',') if x) for item in items] TypeError: 'dict' object is not callable
– Kumar P
Jan 3 at 9:29
@KumarP, Can't replicate, the example I give works fine and is identical to your input.
– jpp
Jan 3 at 9:30
@KumarP, It's probably because you've defined a variabledict
earlier. Don't do this. Used_
,dict_
,dct
, or something else.
– jpp
Jan 3 at 9:30
TypeError Traceback (most recent call last) <ipython-input-367-dcc148ac40d3> in <module>() 1 items = (f'rule:{x}' for x in filter(None, gmr.split('rule:'))) ----> 2 res = [dict(x.split(':') for x in item.split(',') if x) for item in items] <ipython-input-367-dcc148ac40d3> in <listcomp>(.0) 1 items = (f'rule:{x}' for x in filter(None, gmr.split('rule:'))) ----> 2 res = [dict(x.split(':') for x in item.split(',') if x) for item in items] TypeError: 'dict' object is not callable
– Kumar P
Jan 3 at 9:29
TypeError Traceback (most recent call last) <ipython-input-367-dcc148ac40d3> in <module>() 1 items = (f'rule:{x}' for x in filter(None, gmr.split('rule:'))) ----> 2 res = [dict(x.split(':') for x in item.split(',') if x) for item in items] <ipython-input-367-dcc148ac40d3> in <listcomp>(.0) 1 items = (f'rule:{x}' for x in filter(None, gmr.split('rule:'))) ----> 2 res = [dict(x.split(':') for x in item.split(',') if x) for item in items] TypeError: 'dict' object is not callable
– Kumar P
Jan 3 at 9:29
@KumarP, Can't replicate, the example I give works fine and is identical to your input.
– jpp
Jan 3 at 9:30
@KumarP, Can't replicate, the example I give works fine and is identical to your input.
– jpp
Jan 3 at 9:30
@KumarP, It's probably because you've defined a variable
dict
earlier. Don't do this. Use d_
, dict_
, dct
, or something else.– jpp
Jan 3 at 9:30
@KumarP, It's probably because you've defined a variable
dict
earlier. Don't do this. Use d_
, dict_
, dct
, or something else.– jpp
Jan 3 at 9:30
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54018874%2fconvert-a-string-to-list-of-dictionaries%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown