Adding the values in a python list in between two dictionaries
I have list of integers. In that list there are two dictionaries like so:
value_list = [1180, 1190, 1190, {'low': 1180}, 1130, 1130, 1180, {'low':1160}, 1130]
The output I am trying to get is the sum of the values in between the two dictionaries, as well as the values of the dictionaries. For example:
for item in value_list:
# if item in list is a dict, sum its value
# with value of next dict and values in between
In this case the output would be 5780
One method I thought of is finding the index number of the two dicts and using them like this:
value_list[3]['low'] + sum(value_list[4:7]) + value_list[7]['low']
But that seems way too convoluted
python list loops dictionary sum
add a comment |
I have list of integers. In that list there are two dictionaries like so:
value_list = [1180, 1190, 1190, {'low': 1180}, 1130, 1130, 1180, {'low':1160}, 1130]
The output I am trying to get is the sum of the values in between the two dictionaries, as well as the values of the dictionaries. For example:
for item in value_list:
# if item in list is a dict, sum its value
# with value of next dict and values in between
In this case the output would be 5780
One method I thought of is finding the index number of the two dicts and using them like this:
value_list[3]['low'] + sum(value_list[4:7]) + value_list[7]['low']
But that seems way too convoluted
python list loops dictionary sum
add a comment |
I have list of integers. In that list there are two dictionaries like so:
value_list = [1180, 1190, 1190, {'low': 1180}, 1130, 1130, 1180, {'low':1160}, 1130]
The output I am trying to get is the sum of the values in between the two dictionaries, as well as the values of the dictionaries. For example:
for item in value_list:
# if item in list is a dict, sum its value
# with value of next dict and values in between
In this case the output would be 5780
One method I thought of is finding the index number of the two dicts and using them like this:
value_list[3]['low'] + sum(value_list[4:7]) + value_list[7]['low']
But that seems way too convoluted
python list loops dictionary sum
I have list of integers. In that list there are two dictionaries like so:
value_list = [1180, 1190, 1190, {'low': 1180}, 1130, 1130, 1180, {'low':1160}, 1130]
The output I am trying to get is the sum of the values in between the two dictionaries, as well as the values of the dictionaries. For example:
for item in value_list:
# if item in list is a dict, sum its value
# with value of next dict and values in between
In this case the output would be 5780
One method I thought of is finding the index number of the two dicts and using them like this:
value_list[3]['low'] + sum(value_list[4:7]) + value_list[7]['low']
But that seems way too convoluted
python list loops dictionary sum
python list loops dictionary sum
edited Nov 13 '18 at 19:27
Barmar
425k35248350
425k35248350
asked Nov 13 '18 at 19:26
louielouielouielouielouielouie
245
245
add a comment |
add a comment |
6 Answers
6
active
oldest
votes
You could use the following code, assuming the only types you have are int and dict, and the dict will always have the same format:
total_sum = 0
dicts_num = 0 #flag for checking how many dicts have appeared
for value in value_list:
if isinstance(value, dict):
dicts_num += 1
total_sum += value["low"]
elif (dicts_num == 1):
total_sum += value
1
This worked for me! I only have to worry about integers in this list
– louielouielouie
Nov 13 '18 at 19:48
add a comment |
if you have the indices (indexes?) of the dict objects, you can use them in a list comprehension:
sum([x if type(x)==int else x['low'] for x in value_list[3:8]])
add a comment |
You can use a loop with a flag variable
found_dict = False
total = 0
for i in value_list:
if found_dict:
if type(i) is dict:
total += i['low']
break
else:
total += i
elif type(i) is dict:
total += i['low']
found_dict = True
add a comment |
Quick and lazy solution, although I'm sure I'll catch some flak for not catching and handling exceptions properly
fl = 0
s = 0
for i in value_list:
if fl == 0:
if type(i) == dict:
s += i['low']
fl = 1
continue
if fl == 1:
try:
s += i
except:
s += i['low']
fl = 0
add a comment |
You can extract the indices of the dicts and use a function to extract value if needed
def int_or_value(item, key='low'):
if isinstance(item, int):
return item
else:
return item[key]
value_list = [1180, 1190, 1190, {'low': 1180}, 1130, 1130, 1180, {'low':1160}, 1130]
indices = [index for index, value in enumerate(value_list) if isinstance(value, dict)]
# Use this if you have multiple instances of {dict} ... {dict} to sum in you value_list
for start, stop in (indices[n:n+2] for n in range(0, len(indices), 2)):
print(sum(int_or_value(item) for item in value_list[start:stop+1]))
# If you are sure there is going to be a single instance of {dict} ... {dict} to sum just access indices directly
print(sum(int_or_value(item) fro item in value_list[indices[0]:indices[1]+1]))
add a comment |
Assuming there are only numeric values between the first and last dicts in the value_list:
value_list = [1180, 1190, 1190, {'low': 1180}, 1130, 1130, 1180, {'low':1160}, 1130]
dicts = [(i, list(d.values())[0]) for i, d in enumerate(value_list) if isinstance(d, dict)]
sum(value_list[dicts[0][0] + 1 : dicts[-1][0]]) + sum(t[-1] for t in dicts)
# Outputs: 5780
If the assumption is not correct this needs to be more complex.
You are correct on that assumption!
– louielouielouie
Nov 13 '18 at 19:41
hmm, getting invalid syntax, it points at theforin thedictsvariable, running python 3.x
– louielouielouie
Nov 13 '18 at 19:45
@louielouielouie Ah, sorry, copy-paste error, I fixed the syntax, please try again.
– mVChr
Nov 14 '18 at 18:36
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%2f53288181%2fadding-the-values-in-a-python-list-in-between-two-dictionaries%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
6 Answers
6
active
oldest
votes
6 Answers
6
active
oldest
votes
active
oldest
votes
active
oldest
votes
You could use the following code, assuming the only types you have are int and dict, and the dict will always have the same format:
total_sum = 0
dicts_num = 0 #flag for checking how many dicts have appeared
for value in value_list:
if isinstance(value, dict):
dicts_num += 1
total_sum += value["low"]
elif (dicts_num == 1):
total_sum += value
1
This worked for me! I only have to worry about integers in this list
– louielouielouie
Nov 13 '18 at 19:48
add a comment |
You could use the following code, assuming the only types you have are int and dict, and the dict will always have the same format:
total_sum = 0
dicts_num = 0 #flag for checking how many dicts have appeared
for value in value_list:
if isinstance(value, dict):
dicts_num += 1
total_sum += value["low"]
elif (dicts_num == 1):
total_sum += value
1
This worked for me! I only have to worry about integers in this list
– louielouielouie
Nov 13 '18 at 19:48
add a comment |
You could use the following code, assuming the only types you have are int and dict, and the dict will always have the same format:
total_sum = 0
dicts_num = 0 #flag for checking how many dicts have appeared
for value in value_list:
if isinstance(value, dict):
dicts_num += 1
total_sum += value["low"]
elif (dicts_num == 1):
total_sum += value
You could use the following code, assuming the only types you have are int and dict, and the dict will always have the same format:
total_sum = 0
dicts_num = 0 #flag for checking how many dicts have appeared
for value in value_list:
if isinstance(value, dict):
dicts_num += 1
total_sum += value["low"]
elif (dicts_num == 1):
total_sum += value
answered Nov 13 '18 at 19:44
Luan NaufalLuan Naufal
4908
4908
1
This worked for me! I only have to worry about integers in this list
– louielouielouie
Nov 13 '18 at 19:48
add a comment |
1
This worked for me! I only have to worry about integers in this list
– louielouielouie
Nov 13 '18 at 19:48
1
1
This worked for me! I only have to worry about integers in this list
– louielouielouie
Nov 13 '18 at 19:48
This worked for me! I only have to worry about integers in this list
– louielouielouie
Nov 13 '18 at 19:48
add a comment |
if you have the indices (indexes?) of the dict objects, you can use them in a list comprehension:
sum([x if type(x)==int else x['low'] for x in value_list[3:8]])
add a comment |
if you have the indices (indexes?) of the dict objects, you can use them in a list comprehension:
sum([x if type(x)==int else x['low'] for x in value_list[3:8]])
add a comment |
if you have the indices (indexes?) of the dict objects, you can use them in a list comprehension:
sum([x if type(x)==int else x['low'] for x in value_list[3:8]])
if you have the indices (indexes?) of the dict objects, you can use them in a list comprehension:
sum([x if type(x)==int else x['low'] for x in value_list[3:8]])
answered Nov 13 '18 at 19:37
m0etazm0etaz
392211
392211
add a comment |
add a comment |
You can use a loop with a flag variable
found_dict = False
total = 0
for i in value_list:
if found_dict:
if type(i) is dict:
total += i['low']
break
else:
total += i
elif type(i) is dict:
total += i['low']
found_dict = True
add a comment |
You can use a loop with a flag variable
found_dict = False
total = 0
for i in value_list:
if found_dict:
if type(i) is dict:
total += i['low']
break
else:
total += i
elif type(i) is dict:
total += i['low']
found_dict = True
add a comment |
You can use a loop with a flag variable
found_dict = False
total = 0
for i in value_list:
if found_dict:
if type(i) is dict:
total += i['low']
break
else:
total += i
elif type(i) is dict:
total += i['low']
found_dict = True
You can use a loop with a flag variable
found_dict = False
total = 0
for i in value_list:
if found_dict:
if type(i) is dict:
total += i['low']
break
else:
total += i
elif type(i) is dict:
total += i['low']
found_dict = True
edited Nov 13 '18 at 19:38
answered Nov 13 '18 at 19:31
BarmarBarmar
425k35248350
425k35248350
add a comment |
add a comment |
Quick and lazy solution, although I'm sure I'll catch some flak for not catching and handling exceptions properly
fl = 0
s = 0
for i in value_list:
if fl == 0:
if type(i) == dict:
s += i['low']
fl = 1
continue
if fl == 1:
try:
s += i
except:
s += i['low']
fl = 0
add a comment |
Quick and lazy solution, although I'm sure I'll catch some flak for not catching and handling exceptions properly
fl = 0
s = 0
for i in value_list:
if fl == 0:
if type(i) == dict:
s += i['low']
fl = 1
continue
if fl == 1:
try:
s += i
except:
s += i['low']
fl = 0
add a comment |
Quick and lazy solution, although I'm sure I'll catch some flak for not catching and handling exceptions properly
fl = 0
s = 0
for i in value_list:
if fl == 0:
if type(i) == dict:
s += i['low']
fl = 1
continue
if fl == 1:
try:
s += i
except:
s += i['low']
fl = 0
Quick and lazy solution, although I'm sure I'll catch some flak for not catching and handling exceptions properly
fl = 0
s = 0
for i in value_list:
if fl == 0:
if type(i) == dict:
s += i['low']
fl = 1
continue
if fl == 1:
try:
s += i
except:
s += i['low']
fl = 0
answered Nov 13 '18 at 19:40
UsernamenotfoundUsernamenotfound
1,0771416
1,0771416
add a comment |
add a comment |
You can extract the indices of the dicts and use a function to extract value if needed
def int_or_value(item, key='low'):
if isinstance(item, int):
return item
else:
return item[key]
value_list = [1180, 1190, 1190, {'low': 1180}, 1130, 1130, 1180, {'low':1160}, 1130]
indices = [index for index, value in enumerate(value_list) if isinstance(value, dict)]
# Use this if you have multiple instances of {dict} ... {dict} to sum in you value_list
for start, stop in (indices[n:n+2] for n in range(0, len(indices), 2)):
print(sum(int_or_value(item) for item in value_list[start:stop+1]))
# If you are sure there is going to be a single instance of {dict} ... {dict} to sum just access indices directly
print(sum(int_or_value(item) fro item in value_list[indices[0]:indices[1]+1]))
add a comment |
You can extract the indices of the dicts and use a function to extract value if needed
def int_or_value(item, key='low'):
if isinstance(item, int):
return item
else:
return item[key]
value_list = [1180, 1190, 1190, {'low': 1180}, 1130, 1130, 1180, {'low':1160}, 1130]
indices = [index for index, value in enumerate(value_list) if isinstance(value, dict)]
# Use this if you have multiple instances of {dict} ... {dict} to sum in you value_list
for start, stop in (indices[n:n+2] for n in range(0, len(indices), 2)):
print(sum(int_or_value(item) for item in value_list[start:stop+1]))
# If you are sure there is going to be a single instance of {dict} ... {dict} to sum just access indices directly
print(sum(int_or_value(item) fro item in value_list[indices[0]:indices[1]+1]))
add a comment |
You can extract the indices of the dicts and use a function to extract value if needed
def int_or_value(item, key='low'):
if isinstance(item, int):
return item
else:
return item[key]
value_list = [1180, 1190, 1190, {'low': 1180}, 1130, 1130, 1180, {'low':1160}, 1130]
indices = [index for index, value in enumerate(value_list) if isinstance(value, dict)]
# Use this if you have multiple instances of {dict} ... {dict} to sum in you value_list
for start, stop in (indices[n:n+2] for n in range(0, len(indices), 2)):
print(sum(int_or_value(item) for item in value_list[start:stop+1]))
# If you are sure there is going to be a single instance of {dict} ... {dict} to sum just access indices directly
print(sum(int_or_value(item) fro item in value_list[indices[0]:indices[1]+1]))
You can extract the indices of the dicts and use a function to extract value if needed
def int_or_value(item, key='low'):
if isinstance(item, int):
return item
else:
return item[key]
value_list = [1180, 1190, 1190, {'low': 1180}, 1130, 1130, 1180, {'low':1160}, 1130]
indices = [index for index, value in enumerate(value_list) if isinstance(value, dict)]
# Use this if you have multiple instances of {dict} ... {dict} to sum in you value_list
for start, stop in (indices[n:n+2] for n in range(0, len(indices), 2)):
print(sum(int_or_value(item) for item in value_list[start:stop+1]))
# If you are sure there is going to be a single instance of {dict} ... {dict} to sum just access indices directly
print(sum(int_or_value(item) fro item in value_list[indices[0]:indices[1]+1]))
answered Nov 13 '18 at 19:44
DalvenjiaDalvenjia
1,0231612
1,0231612
add a comment |
add a comment |
Assuming there are only numeric values between the first and last dicts in the value_list:
value_list = [1180, 1190, 1190, {'low': 1180}, 1130, 1130, 1180, {'low':1160}, 1130]
dicts = [(i, list(d.values())[0]) for i, d in enumerate(value_list) if isinstance(d, dict)]
sum(value_list[dicts[0][0] + 1 : dicts[-1][0]]) + sum(t[-1] for t in dicts)
# Outputs: 5780
If the assumption is not correct this needs to be more complex.
You are correct on that assumption!
– louielouielouie
Nov 13 '18 at 19:41
hmm, getting invalid syntax, it points at theforin thedictsvariable, running python 3.x
– louielouielouie
Nov 13 '18 at 19:45
@louielouielouie Ah, sorry, copy-paste error, I fixed the syntax, please try again.
– mVChr
Nov 14 '18 at 18:36
add a comment |
Assuming there are only numeric values between the first and last dicts in the value_list:
value_list = [1180, 1190, 1190, {'low': 1180}, 1130, 1130, 1180, {'low':1160}, 1130]
dicts = [(i, list(d.values())[0]) for i, d in enumerate(value_list) if isinstance(d, dict)]
sum(value_list[dicts[0][0] + 1 : dicts[-1][0]]) + sum(t[-1] for t in dicts)
# Outputs: 5780
If the assumption is not correct this needs to be more complex.
You are correct on that assumption!
– louielouielouie
Nov 13 '18 at 19:41
hmm, getting invalid syntax, it points at theforin thedictsvariable, running python 3.x
– louielouielouie
Nov 13 '18 at 19:45
@louielouielouie Ah, sorry, copy-paste error, I fixed the syntax, please try again.
– mVChr
Nov 14 '18 at 18:36
add a comment |
Assuming there are only numeric values between the first and last dicts in the value_list:
value_list = [1180, 1190, 1190, {'low': 1180}, 1130, 1130, 1180, {'low':1160}, 1130]
dicts = [(i, list(d.values())[0]) for i, d in enumerate(value_list) if isinstance(d, dict)]
sum(value_list[dicts[0][0] + 1 : dicts[-1][0]]) + sum(t[-1] for t in dicts)
# Outputs: 5780
If the assumption is not correct this needs to be more complex.
Assuming there are only numeric values between the first and last dicts in the value_list:
value_list = [1180, 1190, 1190, {'low': 1180}, 1130, 1130, 1180, {'low':1160}, 1130]
dicts = [(i, list(d.values())[0]) for i, d in enumerate(value_list) if isinstance(d, dict)]
sum(value_list[dicts[0][0] + 1 : dicts[-1][0]]) + sum(t[-1] for t in dicts)
# Outputs: 5780
If the assumption is not correct this needs to be more complex.
edited Nov 14 '18 at 18:36
answered Nov 13 '18 at 19:37
mVChrmVChr
40.6k78490
40.6k78490
You are correct on that assumption!
– louielouielouie
Nov 13 '18 at 19:41
hmm, getting invalid syntax, it points at theforin thedictsvariable, running python 3.x
– louielouielouie
Nov 13 '18 at 19:45
@louielouielouie Ah, sorry, copy-paste error, I fixed the syntax, please try again.
– mVChr
Nov 14 '18 at 18:36
add a comment |
You are correct on that assumption!
– louielouielouie
Nov 13 '18 at 19:41
hmm, getting invalid syntax, it points at theforin thedictsvariable, running python 3.x
– louielouielouie
Nov 13 '18 at 19:45
@louielouielouie Ah, sorry, copy-paste error, I fixed the syntax, please try again.
– mVChr
Nov 14 '18 at 18:36
You are correct on that assumption!
– louielouielouie
Nov 13 '18 at 19:41
You are correct on that assumption!
– louielouielouie
Nov 13 '18 at 19:41
hmm, getting invalid syntax, it points at the
for in the dicts variable, running python 3.x– louielouielouie
Nov 13 '18 at 19:45
hmm, getting invalid syntax, it points at the
for in the dicts variable, running python 3.x– louielouielouie
Nov 13 '18 at 19:45
@louielouielouie Ah, sorry, copy-paste error, I fixed the syntax, please try again.
– mVChr
Nov 14 '18 at 18:36
@louielouielouie Ah, sorry, copy-paste error, I fixed the syntax, please try again.
– mVChr
Nov 14 '18 at 18:36
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%2f53288181%2fadding-the-values-in-a-python-list-in-between-two-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