Dictionary: Subtracting the 1st entry from the 2nd in a series of dictionary values
I have a dictionary like this, with thousands more keys than shown, and hundreds of values for each letter a, b, c:
dictex = {'cat': {'a': [[1, 3, 5], [2, 2, 7]], 'b': [[1, 3, 7], [2, 2, 7]], 'c': [[1, 2, 7], [2, 2, 7]]},
'dog': {'a': [[1, 2, 5], [2, 2, 7]], 'b': [[1, 2, 7], [2, 2, 7]], 'c': [[1, 3, 7], [2, 2, 7]]},
'moose': {'a': [[1, 1, 5], [2, 2, 7]], 'b': [[1, 1, 7], [2, 2, 7]], 'c': [[1, 1, 7], [2, 2, 7]]}}
I want to subtract the 1st value from the 2nd value for every entry, and sum across all a, all b, and all c. For example, for the cat entry of a, the operation is (5-3) + (7-2). The preferred output is (.csv):
animal a b c
cat 7 9 10
dog 8 10 9
moose 9 11 11
I can get a particular animal and letter difference using
dictex['cat']['a'][0][2] - dictex['cat']['a'][0][1]`
output:
2
I'm not sure how to get this for every entry in a smart way that doesn't require a lot of manual entry, and then output it into the above form.
python dictionary
add a comment |
I have a dictionary like this, with thousands more keys than shown, and hundreds of values for each letter a, b, c:
dictex = {'cat': {'a': [[1, 3, 5], [2, 2, 7]], 'b': [[1, 3, 7], [2, 2, 7]], 'c': [[1, 2, 7], [2, 2, 7]]},
'dog': {'a': [[1, 2, 5], [2, 2, 7]], 'b': [[1, 2, 7], [2, 2, 7]], 'c': [[1, 3, 7], [2, 2, 7]]},
'moose': {'a': [[1, 1, 5], [2, 2, 7]], 'b': [[1, 1, 7], [2, 2, 7]], 'c': [[1, 1, 7], [2, 2, 7]]}}
I want to subtract the 1st value from the 2nd value for every entry, and sum across all a, all b, and all c. For example, for the cat entry of a, the operation is (5-3) + (7-2). The preferred output is (.csv):
animal a b c
cat 7 9 10
dog 8 10 9
moose 9 11 11
I can get a particular animal and letter difference using
dictex['cat']['a'][0][2] - dictex['cat']['a'][0][1]`
output:
2
I'm not sure how to get this for every entry in a smart way that doesn't require a lot of manual entry, and then output it into the above form.
python dictionary
I understand how you arrive at the itermediary result with cat, a -> 7, but what do you mean by "and sum across letters a, b, c", where is that step?
– timgeb
Nov 27 '18 at 21:59
That's unclear, sorry. I meant sum across alla, then sum across allb, etc. Edited for clarity.
– Liquidity
Nov 27 '18 at 22:01
So the output you posted is the desired output or do you need another column with the sums, e.g. 7+9+10, then 8+10+9, ... ?
– timgeb
Nov 27 '18 at 22:02
Nope, no overall sum. Just the output I posted.
– Liquidity
Nov 27 '18 at 22:06
add a comment |
I have a dictionary like this, with thousands more keys than shown, and hundreds of values for each letter a, b, c:
dictex = {'cat': {'a': [[1, 3, 5], [2, 2, 7]], 'b': [[1, 3, 7], [2, 2, 7]], 'c': [[1, 2, 7], [2, 2, 7]]},
'dog': {'a': [[1, 2, 5], [2, 2, 7]], 'b': [[1, 2, 7], [2, 2, 7]], 'c': [[1, 3, 7], [2, 2, 7]]},
'moose': {'a': [[1, 1, 5], [2, 2, 7]], 'b': [[1, 1, 7], [2, 2, 7]], 'c': [[1, 1, 7], [2, 2, 7]]}}
I want to subtract the 1st value from the 2nd value for every entry, and sum across all a, all b, and all c. For example, for the cat entry of a, the operation is (5-3) + (7-2). The preferred output is (.csv):
animal a b c
cat 7 9 10
dog 8 10 9
moose 9 11 11
I can get a particular animal and letter difference using
dictex['cat']['a'][0][2] - dictex['cat']['a'][0][1]`
output:
2
I'm not sure how to get this for every entry in a smart way that doesn't require a lot of manual entry, and then output it into the above form.
python dictionary
I have a dictionary like this, with thousands more keys than shown, and hundreds of values for each letter a, b, c:
dictex = {'cat': {'a': [[1, 3, 5], [2, 2, 7]], 'b': [[1, 3, 7], [2, 2, 7]], 'c': [[1, 2, 7], [2, 2, 7]]},
'dog': {'a': [[1, 2, 5], [2, 2, 7]], 'b': [[1, 2, 7], [2, 2, 7]], 'c': [[1, 3, 7], [2, 2, 7]]},
'moose': {'a': [[1, 1, 5], [2, 2, 7]], 'b': [[1, 1, 7], [2, 2, 7]], 'c': [[1, 1, 7], [2, 2, 7]]}}
I want to subtract the 1st value from the 2nd value for every entry, and sum across all a, all b, and all c. For example, for the cat entry of a, the operation is (5-3) + (7-2). The preferred output is (.csv):
animal a b c
cat 7 9 10
dog 8 10 9
moose 9 11 11
I can get a particular animal and letter difference using
dictex['cat']['a'][0][2] - dictex['cat']['a'][0][1]`
output:
2
I'm not sure how to get this for every entry in a smart way that doesn't require a lot of manual entry, and then output it into the above form.
python dictionary
python dictionary
edited Nov 27 '18 at 22:12
timgeb
51.1k116694
51.1k116694
asked Nov 27 '18 at 21:53
LiquidityLiquidity
266212
266212
I understand how you arrive at the itermediary result with cat, a -> 7, but what do you mean by "and sum across letters a, b, c", where is that step?
– timgeb
Nov 27 '18 at 21:59
That's unclear, sorry. I meant sum across alla, then sum across allb, etc. Edited for clarity.
– Liquidity
Nov 27 '18 at 22:01
So the output you posted is the desired output or do you need another column with the sums, e.g. 7+9+10, then 8+10+9, ... ?
– timgeb
Nov 27 '18 at 22:02
Nope, no overall sum. Just the output I posted.
– Liquidity
Nov 27 '18 at 22:06
add a comment |
I understand how you arrive at the itermediary result with cat, a -> 7, but what do you mean by "and sum across letters a, b, c", where is that step?
– timgeb
Nov 27 '18 at 21:59
That's unclear, sorry. I meant sum across alla, then sum across allb, etc. Edited for clarity.
– Liquidity
Nov 27 '18 at 22:01
So the output you posted is the desired output or do you need another column with the sums, e.g. 7+9+10, then 8+10+9, ... ?
– timgeb
Nov 27 '18 at 22:02
Nope, no overall sum. Just the output I posted.
– Liquidity
Nov 27 '18 at 22:06
I understand how you arrive at the itermediary result with cat, a -> 7, but what do you mean by "and sum across letters a, b, c", where is that step?
– timgeb
Nov 27 '18 at 21:59
I understand how you arrive at the itermediary result with cat, a -> 7, but what do you mean by "and sum across letters a, b, c", where is that step?
– timgeb
Nov 27 '18 at 21:59
That's unclear, sorry. I meant sum across all
a, then sum across all b, etc. Edited for clarity.– Liquidity
Nov 27 '18 at 22:01
That's unclear, sorry. I meant sum across all
a, then sum across all b, etc. Edited for clarity.– Liquidity
Nov 27 '18 at 22:01
So the output you posted is the desired output or do you need another column with the sums, e.g. 7+9+10, then 8+10+9, ... ?
– timgeb
Nov 27 '18 at 22:02
So the output you posted is the desired output or do you need another column with the sums, e.g. 7+9+10, then 8+10+9, ... ?
– timgeb
Nov 27 '18 at 22:02
Nope, no overall sum. Just the output I posted.
– Liquidity
Nov 27 '18 at 22:06
Nope, no overall sum. Just the output I posted.
– Liquidity
Nov 27 '18 at 22:06
add a comment |
3 Answers
3
active
oldest
votes
It can be written quite sunccintly with pandas if you can use that library.
Usually putting lists into dataframes is not such a good idea, but we only do some mild processing and then save the result to a csv file.
pd.DataFrame(dictex).rename_axis('animal', 1).applymap(lambda lists: sum(l[2]-l[1] for l in lists)).T.to_csv('f.csv')
This results in the file
animal,a,b,c
cat,7,9,10
dog,8,10,9
moose,9,11,11
add a comment |
You can define a separate method to get the sum of all differences between the 2nd and 1st elements of all lists in a list and then generate your result with a "dictionary comprehension":
def diff_sums(l):
return sum(x[2] - x[1] for x in l)
dictex = {'cat': {'a': [[1, 3, 5], [2, 2, 7]], 'b': [[1, 3, 7], [2, 2, 7]], 'c': [[1, 2, 7], [2, 2, 7]]},
'dog': {'a': [[1, 2, 5], [2, 2, 7]], 'b': [[1, 2, 7], [2, 2, 7]], 'c': [[1, 3, 7], [2, 2, 7]]},
'moose': {'a': [[1, 1, 5], [2, 2, 7]], 'b': [[1, 1, 7], [2, 2, 7]], 'c': [[1, 1, 7], [2, 2, 7]]}}
result = {animal: {k: diff_sums(v) for k, v in num_lists.items()} for animal, num_lists in dictex.items()}
print(result)
Output
{'cat': {'a': 7, 'b': 9, 'c': 10},
'dog': {'a': 8, 'b': 10, 'c': 9},
'moose': {'a': 9, 'b': 11, 'c': 11}}
To write this to a CSV file, you can use the csv module:
import csv
columns = ['animal', 'a', 'b', 'c']
data = [[animal] + [v[c] for c in columns[1:]] for animal, v in result.items()]
with open('mydata.csv', 'w') as csvfile:
writer = csv.writer(csvfile, delimiter=',')
for line in [columns] + data:
writer.writerow(line)
Output
animal,a,b,c
cat,7,9,10
dog,8,10,9
moose,9,11,11
add a comment |
If you find yourself having to do a certain calculation over and over, then that's when it's probably best to write a function. Here's a function that takes a dictionary like dictex, an animal name, and a letter, and returns the individual calculation for you:
# Do the calculations for a particular animal and letter
def calculate_value(mydict, animal, letter):
W = mydict[animal][letter][0][2]
X = mydict[animal][letter][0][1]
Y = mydict[animal][letter][1][2]
Z = mydict[animal][letter][1][1]
# Do the math and convert the resulting number to a string,
# which will save us some headaches when writing to the csv file.
return str((W-X) + (Y-Z))
Here's a function that goes through the entire dictionary, calculates the values for each animal and letter, then finally returns the result in a list of lists that looks like this: [ ['cat',7,9,10], ['dog',8,10,9], ... ] etc.
def make_new_list(my_dict):
new_list =
for animal in my_dict:
individual_animal_list = [animal]
for letter in ['a', 'b', 'c']:
individual_animal_list.append(calculate_value(my_dict, animal, letter))
new_list.append(individual_animal_list)
return new_list
The reason why I used the format above, is because it makes it much easier to write the result to a csv file. Just take each list you got from the previous function, join everything together with commas in between, and write it as a row to the file:
dictex = {'cat': {'a': [[1, 3, 5], [2, 2, 7]], 'b': [[1, 3, 7], [2, 2, 7]], 'c': [[1, 2, 7], [2, 2, 7]]},
'dog': {'a': [[1, 2, 5], [2, 2, 7]], 'b': [[1, 2, 7], [2, 2, 7]], 'c': [[1, 3, 7], [2, 2, 7]]},
'moose': {'a': [[1, 1, 5], [2, 2, 7]], 'b': [[1, 1, 7], [2, 2, 7]], 'c': [[1, 1, 7], [2, 2, 7]]}}
new_list = make_new_list(dictex)
with open('my_file.csv', 'w') as f:
f.write('animal,a,b,cn') # Write the header line
for row in new_list:
f.write(','.join(row))
f.write('n')
Keep in mind that dictionaries in Python are NOT ordered. So your resulting file is not necessarily going to have your animal rows in the same order as they appear in your original dictionary.
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%2f53508765%2fdictionary-subtracting-the-1st-entry-from-the-2nd-in-a-series-of-dictionary-val%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
It can be written quite sunccintly with pandas if you can use that library.
Usually putting lists into dataframes is not such a good idea, but we only do some mild processing and then save the result to a csv file.
pd.DataFrame(dictex).rename_axis('animal', 1).applymap(lambda lists: sum(l[2]-l[1] for l in lists)).T.to_csv('f.csv')
This results in the file
animal,a,b,c
cat,7,9,10
dog,8,10,9
moose,9,11,11
add a comment |
It can be written quite sunccintly with pandas if you can use that library.
Usually putting lists into dataframes is not such a good idea, but we only do some mild processing and then save the result to a csv file.
pd.DataFrame(dictex).rename_axis('animal', 1).applymap(lambda lists: sum(l[2]-l[1] for l in lists)).T.to_csv('f.csv')
This results in the file
animal,a,b,c
cat,7,9,10
dog,8,10,9
moose,9,11,11
add a comment |
It can be written quite sunccintly with pandas if you can use that library.
Usually putting lists into dataframes is not such a good idea, but we only do some mild processing and then save the result to a csv file.
pd.DataFrame(dictex).rename_axis('animal', 1).applymap(lambda lists: sum(l[2]-l[1] for l in lists)).T.to_csv('f.csv')
This results in the file
animal,a,b,c
cat,7,9,10
dog,8,10,9
moose,9,11,11
It can be written quite sunccintly with pandas if you can use that library.
Usually putting lists into dataframes is not such a good idea, but we only do some mild processing and then save the result to a csv file.
pd.DataFrame(dictex).rename_axis('animal', 1).applymap(lambda lists: sum(l[2]-l[1] for l in lists)).T.to_csv('f.csv')
This results in the file
animal,a,b,c
cat,7,9,10
dog,8,10,9
moose,9,11,11
answered Nov 27 '18 at 22:11
timgebtimgeb
51.1k116694
51.1k116694
add a comment |
add a comment |
You can define a separate method to get the sum of all differences between the 2nd and 1st elements of all lists in a list and then generate your result with a "dictionary comprehension":
def diff_sums(l):
return sum(x[2] - x[1] for x in l)
dictex = {'cat': {'a': [[1, 3, 5], [2, 2, 7]], 'b': [[1, 3, 7], [2, 2, 7]], 'c': [[1, 2, 7], [2, 2, 7]]},
'dog': {'a': [[1, 2, 5], [2, 2, 7]], 'b': [[1, 2, 7], [2, 2, 7]], 'c': [[1, 3, 7], [2, 2, 7]]},
'moose': {'a': [[1, 1, 5], [2, 2, 7]], 'b': [[1, 1, 7], [2, 2, 7]], 'c': [[1, 1, 7], [2, 2, 7]]}}
result = {animal: {k: diff_sums(v) for k, v in num_lists.items()} for animal, num_lists in dictex.items()}
print(result)
Output
{'cat': {'a': 7, 'b': 9, 'c': 10},
'dog': {'a': 8, 'b': 10, 'c': 9},
'moose': {'a': 9, 'b': 11, 'c': 11}}
To write this to a CSV file, you can use the csv module:
import csv
columns = ['animal', 'a', 'b', 'c']
data = [[animal] + [v[c] for c in columns[1:]] for animal, v in result.items()]
with open('mydata.csv', 'w') as csvfile:
writer = csv.writer(csvfile, delimiter=',')
for line in [columns] + data:
writer.writerow(line)
Output
animal,a,b,c
cat,7,9,10
dog,8,10,9
moose,9,11,11
add a comment |
You can define a separate method to get the sum of all differences between the 2nd and 1st elements of all lists in a list and then generate your result with a "dictionary comprehension":
def diff_sums(l):
return sum(x[2] - x[1] for x in l)
dictex = {'cat': {'a': [[1, 3, 5], [2, 2, 7]], 'b': [[1, 3, 7], [2, 2, 7]], 'c': [[1, 2, 7], [2, 2, 7]]},
'dog': {'a': [[1, 2, 5], [2, 2, 7]], 'b': [[1, 2, 7], [2, 2, 7]], 'c': [[1, 3, 7], [2, 2, 7]]},
'moose': {'a': [[1, 1, 5], [2, 2, 7]], 'b': [[1, 1, 7], [2, 2, 7]], 'c': [[1, 1, 7], [2, 2, 7]]}}
result = {animal: {k: diff_sums(v) for k, v in num_lists.items()} for animal, num_lists in dictex.items()}
print(result)
Output
{'cat': {'a': 7, 'b': 9, 'c': 10},
'dog': {'a': 8, 'b': 10, 'c': 9},
'moose': {'a': 9, 'b': 11, 'c': 11}}
To write this to a CSV file, you can use the csv module:
import csv
columns = ['animal', 'a', 'b', 'c']
data = [[animal] + [v[c] for c in columns[1:]] for animal, v in result.items()]
with open('mydata.csv', 'w') as csvfile:
writer = csv.writer(csvfile, delimiter=',')
for line in [columns] + data:
writer.writerow(line)
Output
animal,a,b,c
cat,7,9,10
dog,8,10,9
moose,9,11,11
add a comment |
You can define a separate method to get the sum of all differences between the 2nd and 1st elements of all lists in a list and then generate your result with a "dictionary comprehension":
def diff_sums(l):
return sum(x[2] - x[1] for x in l)
dictex = {'cat': {'a': [[1, 3, 5], [2, 2, 7]], 'b': [[1, 3, 7], [2, 2, 7]], 'c': [[1, 2, 7], [2, 2, 7]]},
'dog': {'a': [[1, 2, 5], [2, 2, 7]], 'b': [[1, 2, 7], [2, 2, 7]], 'c': [[1, 3, 7], [2, 2, 7]]},
'moose': {'a': [[1, 1, 5], [2, 2, 7]], 'b': [[1, 1, 7], [2, 2, 7]], 'c': [[1, 1, 7], [2, 2, 7]]}}
result = {animal: {k: diff_sums(v) for k, v in num_lists.items()} for animal, num_lists in dictex.items()}
print(result)
Output
{'cat': {'a': 7, 'b': 9, 'c': 10},
'dog': {'a': 8, 'b': 10, 'c': 9},
'moose': {'a': 9, 'b': 11, 'c': 11}}
To write this to a CSV file, you can use the csv module:
import csv
columns = ['animal', 'a', 'b', 'c']
data = [[animal] + [v[c] for c in columns[1:]] for animal, v in result.items()]
with open('mydata.csv', 'w') as csvfile:
writer = csv.writer(csvfile, delimiter=',')
for line in [columns] + data:
writer.writerow(line)
Output
animal,a,b,c
cat,7,9,10
dog,8,10,9
moose,9,11,11
You can define a separate method to get the sum of all differences between the 2nd and 1st elements of all lists in a list and then generate your result with a "dictionary comprehension":
def diff_sums(l):
return sum(x[2] - x[1] for x in l)
dictex = {'cat': {'a': [[1, 3, 5], [2, 2, 7]], 'b': [[1, 3, 7], [2, 2, 7]], 'c': [[1, 2, 7], [2, 2, 7]]},
'dog': {'a': [[1, 2, 5], [2, 2, 7]], 'b': [[1, 2, 7], [2, 2, 7]], 'c': [[1, 3, 7], [2, 2, 7]]},
'moose': {'a': [[1, 1, 5], [2, 2, 7]], 'b': [[1, 1, 7], [2, 2, 7]], 'c': [[1, 1, 7], [2, 2, 7]]}}
result = {animal: {k: diff_sums(v) for k, v in num_lists.items()} for animal, num_lists in dictex.items()}
print(result)
Output
{'cat': {'a': 7, 'b': 9, 'c': 10},
'dog': {'a': 8, 'b': 10, 'c': 9},
'moose': {'a': 9, 'b': 11, 'c': 11}}
To write this to a CSV file, you can use the csv module:
import csv
columns = ['animal', 'a', 'b', 'c']
data = [[animal] + [v[c] for c in columns[1:]] for animal, v in result.items()]
with open('mydata.csv', 'w') as csvfile:
writer = csv.writer(csvfile, delimiter=',')
for line in [columns] + data:
writer.writerow(line)
Output
animal,a,b,c
cat,7,9,10
dog,8,10,9
moose,9,11,11
edited Nov 27 '18 at 22:20
answered Nov 27 '18 at 22:04
sliderslider
8,47311231
8,47311231
add a comment |
add a comment |
If you find yourself having to do a certain calculation over and over, then that's when it's probably best to write a function. Here's a function that takes a dictionary like dictex, an animal name, and a letter, and returns the individual calculation for you:
# Do the calculations for a particular animal and letter
def calculate_value(mydict, animal, letter):
W = mydict[animal][letter][0][2]
X = mydict[animal][letter][0][1]
Y = mydict[animal][letter][1][2]
Z = mydict[animal][letter][1][1]
# Do the math and convert the resulting number to a string,
# which will save us some headaches when writing to the csv file.
return str((W-X) + (Y-Z))
Here's a function that goes through the entire dictionary, calculates the values for each animal and letter, then finally returns the result in a list of lists that looks like this: [ ['cat',7,9,10], ['dog',8,10,9], ... ] etc.
def make_new_list(my_dict):
new_list =
for animal in my_dict:
individual_animal_list = [animal]
for letter in ['a', 'b', 'c']:
individual_animal_list.append(calculate_value(my_dict, animal, letter))
new_list.append(individual_animal_list)
return new_list
The reason why I used the format above, is because it makes it much easier to write the result to a csv file. Just take each list you got from the previous function, join everything together with commas in between, and write it as a row to the file:
dictex = {'cat': {'a': [[1, 3, 5], [2, 2, 7]], 'b': [[1, 3, 7], [2, 2, 7]], 'c': [[1, 2, 7], [2, 2, 7]]},
'dog': {'a': [[1, 2, 5], [2, 2, 7]], 'b': [[1, 2, 7], [2, 2, 7]], 'c': [[1, 3, 7], [2, 2, 7]]},
'moose': {'a': [[1, 1, 5], [2, 2, 7]], 'b': [[1, 1, 7], [2, 2, 7]], 'c': [[1, 1, 7], [2, 2, 7]]}}
new_list = make_new_list(dictex)
with open('my_file.csv', 'w') as f:
f.write('animal,a,b,cn') # Write the header line
for row in new_list:
f.write(','.join(row))
f.write('n')
Keep in mind that dictionaries in Python are NOT ordered. So your resulting file is not necessarily going to have your animal rows in the same order as they appear in your original dictionary.
add a comment |
If you find yourself having to do a certain calculation over and over, then that's when it's probably best to write a function. Here's a function that takes a dictionary like dictex, an animal name, and a letter, and returns the individual calculation for you:
# Do the calculations for a particular animal and letter
def calculate_value(mydict, animal, letter):
W = mydict[animal][letter][0][2]
X = mydict[animal][letter][0][1]
Y = mydict[animal][letter][1][2]
Z = mydict[animal][letter][1][1]
# Do the math and convert the resulting number to a string,
# which will save us some headaches when writing to the csv file.
return str((W-X) + (Y-Z))
Here's a function that goes through the entire dictionary, calculates the values for each animal and letter, then finally returns the result in a list of lists that looks like this: [ ['cat',7,9,10], ['dog',8,10,9], ... ] etc.
def make_new_list(my_dict):
new_list =
for animal in my_dict:
individual_animal_list = [animal]
for letter in ['a', 'b', 'c']:
individual_animal_list.append(calculate_value(my_dict, animal, letter))
new_list.append(individual_animal_list)
return new_list
The reason why I used the format above, is because it makes it much easier to write the result to a csv file. Just take each list you got from the previous function, join everything together with commas in between, and write it as a row to the file:
dictex = {'cat': {'a': [[1, 3, 5], [2, 2, 7]], 'b': [[1, 3, 7], [2, 2, 7]], 'c': [[1, 2, 7], [2, 2, 7]]},
'dog': {'a': [[1, 2, 5], [2, 2, 7]], 'b': [[1, 2, 7], [2, 2, 7]], 'c': [[1, 3, 7], [2, 2, 7]]},
'moose': {'a': [[1, 1, 5], [2, 2, 7]], 'b': [[1, 1, 7], [2, 2, 7]], 'c': [[1, 1, 7], [2, 2, 7]]}}
new_list = make_new_list(dictex)
with open('my_file.csv', 'w') as f:
f.write('animal,a,b,cn') # Write the header line
for row in new_list:
f.write(','.join(row))
f.write('n')
Keep in mind that dictionaries in Python are NOT ordered. So your resulting file is not necessarily going to have your animal rows in the same order as they appear in your original dictionary.
add a comment |
If you find yourself having to do a certain calculation over and over, then that's when it's probably best to write a function. Here's a function that takes a dictionary like dictex, an animal name, and a letter, and returns the individual calculation for you:
# Do the calculations for a particular animal and letter
def calculate_value(mydict, animal, letter):
W = mydict[animal][letter][0][2]
X = mydict[animal][letter][0][1]
Y = mydict[animal][letter][1][2]
Z = mydict[animal][letter][1][1]
# Do the math and convert the resulting number to a string,
# which will save us some headaches when writing to the csv file.
return str((W-X) + (Y-Z))
Here's a function that goes through the entire dictionary, calculates the values for each animal and letter, then finally returns the result in a list of lists that looks like this: [ ['cat',7,9,10], ['dog',8,10,9], ... ] etc.
def make_new_list(my_dict):
new_list =
for animal in my_dict:
individual_animal_list = [animal]
for letter in ['a', 'b', 'c']:
individual_animal_list.append(calculate_value(my_dict, animal, letter))
new_list.append(individual_animal_list)
return new_list
The reason why I used the format above, is because it makes it much easier to write the result to a csv file. Just take each list you got from the previous function, join everything together with commas in between, and write it as a row to the file:
dictex = {'cat': {'a': [[1, 3, 5], [2, 2, 7]], 'b': [[1, 3, 7], [2, 2, 7]], 'c': [[1, 2, 7], [2, 2, 7]]},
'dog': {'a': [[1, 2, 5], [2, 2, 7]], 'b': [[1, 2, 7], [2, 2, 7]], 'c': [[1, 3, 7], [2, 2, 7]]},
'moose': {'a': [[1, 1, 5], [2, 2, 7]], 'b': [[1, 1, 7], [2, 2, 7]], 'c': [[1, 1, 7], [2, 2, 7]]}}
new_list = make_new_list(dictex)
with open('my_file.csv', 'w') as f:
f.write('animal,a,b,cn') # Write the header line
for row in new_list:
f.write(','.join(row))
f.write('n')
Keep in mind that dictionaries in Python are NOT ordered. So your resulting file is not necessarily going to have your animal rows in the same order as they appear in your original dictionary.
If you find yourself having to do a certain calculation over and over, then that's when it's probably best to write a function. Here's a function that takes a dictionary like dictex, an animal name, and a letter, and returns the individual calculation for you:
# Do the calculations for a particular animal and letter
def calculate_value(mydict, animal, letter):
W = mydict[animal][letter][0][2]
X = mydict[animal][letter][0][1]
Y = mydict[animal][letter][1][2]
Z = mydict[animal][letter][1][1]
# Do the math and convert the resulting number to a string,
# which will save us some headaches when writing to the csv file.
return str((W-X) + (Y-Z))
Here's a function that goes through the entire dictionary, calculates the values for each animal and letter, then finally returns the result in a list of lists that looks like this: [ ['cat',7,9,10], ['dog',8,10,9], ... ] etc.
def make_new_list(my_dict):
new_list =
for animal in my_dict:
individual_animal_list = [animal]
for letter in ['a', 'b', 'c']:
individual_animal_list.append(calculate_value(my_dict, animal, letter))
new_list.append(individual_animal_list)
return new_list
The reason why I used the format above, is because it makes it much easier to write the result to a csv file. Just take each list you got from the previous function, join everything together with commas in between, and write it as a row to the file:
dictex = {'cat': {'a': [[1, 3, 5], [2, 2, 7]], 'b': [[1, 3, 7], [2, 2, 7]], 'c': [[1, 2, 7], [2, 2, 7]]},
'dog': {'a': [[1, 2, 5], [2, 2, 7]], 'b': [[1, 2, 7], [2, 2, 7]], 'c': [[1, 3, 7], [2, 2, 7]]},
'moose': {'a': [[1, 1, 5], [2, 2, 7]], 'b': [[1, 1, 7], [2, 2, 7]], 'c': [[1, 1, 7], [2, 2, 7]]}}
new_list = make_new_list(dictex)
with open('my_file.csv', 'w') as f:
f.write('animal,a,b,cn') # Write the header line
for row in new_list:
f.write(','.join(row))
f.write('n')
Keep in mind that dictionaries in Python are NOT ordered. So your resulting file is not necessarily going to have your animal rows in the same order as they appear in your original dictionary.
answered Nov 27 '18 at 22:23
Bill M.Bill M.
889112
889112
add a comment |
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%2f53508765%2fdictionary-subtracting-the-1st-entry-from-the-2nd-in-a-series-of-dictionary-val%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
I understand how you arrive at the itermediary result with cat, a -> 7, but what do you mean by "and sum across letters a, b, c", where is that step?
– timgeb
Nov 27 '18 at 21:59
That's unclear, sorry. I meant sum across all
a, then sum across allb, etc. Edited for clarity.– Liquidity
Nov 27 '18 at 22:01
So the output you posted is the desired output or do you need another column with the sums, e.g. 7+9+10, then 8+10+9, ... ?
– timgeb
Nov 27 '18 at 22:02
Nope, no overall sum. Just the output I posted.
– Liquidity
Nov 27 '18 at 22:06