List of references to items in a dictionary
Is there a way, in python, for me to create a list where each element is a reference to an element in a dictionary? This way, I can maintain a sorted list, while also being able to change the value by indexing into the dictionary.
d = {
'price_one': 12,
'price_two': 13,
'price_three': 5
}
sorted_list = [ptr_to_price_three, ptr_to_price_one, ptr_to_price_two]
print(sorted_list) # [5, 12, 13]
d['price_one'] = 1
sorted_list.sort() # [ptr_to_price_one, ptr_to_price_three, ptr_to_price_two]
print(sorted_list) # [1, 5, 13]
python python-3.x list dictionary pointers
|
show 2 more comments
Is there a way, in python, for me to create a list where each element is a reference to an element in a dictionary? This way, I can maintain a sorted list, while also being able to change the value by indexing into the dictionary.
d = {
'price_one': 12,
'price_two': 13,
'price_three': 5
}
sorted_list = [ptr_to_price_three, ptr_to_price_one, ptr_to_price_two]
print(sorted_list) # [5, 12, 13]
d['price_one'] = 1
sorted_list.sort() # [ptr_to_price_one, ptr_to_price_three, ptr_to_price_two]
print(sorted_list) # [1, 5, 13]
python python-3.x list dictionary pointers
1
Not sure what the actual use case is here, but would it be solved byOrderedDict
? docs.python.org/3/library/…
– JacobIRR
Jan 3 at 0:11
@JacobIRR Interesting. It looks like this could work for me. If I were to change a value in the dictionary, would the order also change?
– bpgeck
Jan 3 at 0:15
1
OrderedDict (and normal dict on python 3.7+ / ipython 3.6+) are insert ordered - the only way to keep them ordered is to create them a-new:d =dict(d.items())
after changing something - which is not really good. Why do you need this and whatfor - how big is the dict? Why not create adef get_ordered_items(d): return sorted(d.values())
funciton?
– Patrick Artner
Jan 3 at 0:21
@PatrickArtner It seems likes I need to resort after every modification anyway so this may be the best option
– bpgeck
Jan 3 at 0:29
1
Are you trying to efficiently maintain a sorted container? Because then you should just use sorted containers
– juanpa.arrivillaga
Jan 3 at 2:33
|
show 2 more comments
Is there a way, in python, for me to create a list where each element is a reference to an element in a dictionary? This way, I can maintain a sorted list, while also being able to change the value by indexing into the dictionary.
d = {
'price_one': 12,
'price_two': 13,
'price_three': 5
}
sorted_list = [ptr_to_price_three, ptr_to_price_one, ptr_to_price_two]
print(sorted_list) # [5, 12, 13]
d['price_one'] = 1
sorted_list.sort() # [ptr_to_price_one, ptr_to_price_three, ptr_to_price_two]
print(sorted_list) # [1, 5, 13]
python python-3.x list dictionary pointers
Is there a way, in python, for me to create a list where each element is a reference to an element in a dictionary? This way, I can maintain a sorted list, while also being able to change the value by indexing into the dictionary.
d = {
'price_one': 12,
'price_two': 13,
'price_three': 5
}
sorted_list = [ptr_to_price_three, ptr_to_price_one, ptr_to_price_two]
print(sorted_list) # [5, 12, 13]
d['price_one'] = 1
sorted_list.sort() # [ptr_to_price_one, ptr_to_price_three, ptr_to_price_two]
print(sorted_list) # [1, 5, 13]
python python-3.x list dictionary pointers
python python-3.x list dictionary pointers
asked Jan 3 at 0:08
bpgeckbpgeck
1,160517
1,160517
1
Not sure what the actual use case is here, but would it be solved byOrderedDict
? docs.python.org/3/library/…
– JacobIRR
Jan 3 at 0:11
@JacobIRR Interesting. It looks like this could work for me. If I were to change a value in the dictionary, would the order also change?
– bpgeck
Jan 3 at 0:15
1
OrderedDict (and normal dict on python 3.7+ / ipython 3.6+) are insert ordered - the only way to keep them ordered is to create them a-new:d =dict(d.items())
after changing something - which is not really good. Why do you need this and whatfor - how big is the dict? Why not create adef get_ordered_items(d): return sorted(d.values())
funciton?
– Patrick Artner
Jan 3 at 0:21
@PatrickArtner It seems likes I need to resort after every modification anyway so this may be the best option
– bpgeck
Jan 3 at 0:29
1
Are you trying to efficiently maintain a sorted container? Because then you should just use sorted containers
– juanpa.arrivillaga
Jan 3 at 2:33
|
show 2 more comments
1
Not sure what the actual use case is here, but would it be solved byOrderedDict
? docs.python.org/3/library/…
– JacobIRR
Jan 3 at 0:11
@JacobIRR Interesting. It looks like this could work for me. If I were to change a value in the dictionary, would the order also change?
– bpgeck
Jan 3 at 0:15
1
OrderedDict (and normal dict on python 3.7+ / ipython 3.6+) are insert ordered - the only way to keep them ordered is to create them a-new:d =dict(d.items())
after changing something - which is not really good. Why do you need this and whatfor - how big is the dict? Why not create adef get_ordered_items(d): return sorted(d.values())
funciton?
– Patrick Artner
Jan 3 at 0:21
@PatrickArtner It seems likes I need to resort after every modification anyway so this may be the best option
– bpgeck
Jan 3 at 0:29
1
Are you trying to efficiently maintain a sorted container? Because then you should just use sorted containers
– juanpa.arrivillaga
Jan 3 at 2:33
1
1
Not sure what the actual use case is here, but would it be solved by
OrderedDict
? docs.python.org/3/library/…– JacobIRR
Jan 3 at 0:11
Not sure what the actual use case is here, but would it be solved by
OrderedDict
? docs.python.org/3/library/…– JacobIRR
Jan 3 at 0:11
@JacobIRR Interesting. It looks like this could work for me. If I were to change a value in the dictionary, would the order also change?
– bpgeck
Jan 3 at 0:15
@JacobIRR Interesting. It looks like this could work for me. If I were to change a value in the dictionary, would the order also change?
– bpgeck
Jan 3 at 0:15
1
1
OrderedDict (and normal dict on python 3.7+ / ipython 3.6+) are insert ordered - the only way to keep them ordered is to create them a-new:
d =dict(d.items())
after changing something - which is not really good. Why do you need this and whatfor - how big is the dict? Why not create a def get_ordered_items(d): return sorted(d.values())
funciton?– Patrick Artner
Jan 3 at 0:21
OrderedDict (and normal dict on python 3.7+ / ipython 3.6+) are insert ordered - the only way to keep them ordered is to create them a-new:
d =dict(d.items())
after changing something - which is not really good. Why do you need this and whatfor - how big is the dict? Why not create a def get_ordered_items(d): return sorted(d.values())
funciton?– Patrick Artner
Jan 3 at 0:21
@PatrickArtner It seems likes I need to resort after every modification anyway so this may be the best option
– bpgeck
Jan 3 at 0:29
@PatrickArtner It seems likes I need to resort after every modification anyway so this may be the best option
– bpgeck
Jan 3 at 0:29
1
1
Are you trying to efficiently maintain a sorted container? Because then you should just use sorted containers
– juanpa.arrivillaga
Jan 3 at 2:33
Are you trying to efficiently maintain a sorted container? Because then you should just use sorted containers
– juanpa.arrivillaga
Jan 3 at 2:33
|
show 2 more comments
3 Answers
3
active
oldest
votes
You mentioned Python in general. You could use a dataframe:
import pandas as pd
d = {
'price_one': 12,
'price_two': 13,
'price_three': 5
}
df = pd.DataFrame(list(d.values()), columns=['val'], index=d.keys())
df.loc['price_one'] = 1
df.sort_values(['val'])
Outputs:
1
Pulling inpandas
(and incredibly heavyweight framework) for this seems a bit much. It's fine if you're usingpandas
anyway, but I wouldn't use it as a go-to solution in general.
– ShadowRanger
Jan 3 at 1:55
add a comment |
Try this:
d = {
'price_one': 12,
'price_two': 13,
'price_three': 5
}
def get_sorted(d):
sorted_list = sorted(list(d.values()))
return tuple(zip(sorted_list, d[key] for key in sorted_list))
# end get_sorted
print(get_sorted(d))
d['price_one'] = 1
print(get_sorted(d))
Note that you would have to call get_sorted(d)
each time...
Also, it returns a tuple of pairs (key, value) sorted with their keys. If you wanted to access say the 3rd value, do get_sorted(d)[2][1]
. The 2
for the third pair, the 1
for the value.
I'm pretty sure this won't work. When this line is executedd['price_one'] = 1
, the value will not change in the list
– bpgeck
Jan 3 at 0:21
I've changed it so it's a function instead. It might not be pretty but it works.
– GeeTransit
Jan 3 at 0:22
Gotcha thanks for the changes
– bpgeck
Jan 3 at 0:29
No problem. If it works, you can help other programmers like you get this answer when they see this question by pressing the checkmark to mark it as a correct answer. Keep up the great work :D
– GeeTransit
Jan 3 at 0:32
add a comment |
The dictionary keys are references to particular entries in a dictionary.
A function to generate a list of dictionary keys in the order of the dictionary entry values is:
def sorted_keys(d):
return sorted(d.keys(), key=lambda k: d[k])
so to access the smallest price in your example:
ks = sorted_keys(d)
smallest = d[ ks[0] ]
The problem is that you have to recalculate your ordering on any insert, change or delete of the dictionary. These would be hard to intercept so better to keep control and recalculate the ordering just when you want to use it.
You could bury all this in a class SortedDict(dict)
that overrides the get function of a 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%2f54014800%2flist-of-references-to-items-in-a-dictionary%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
You mentioned Python in general. You could use a dataframe:
import pandas as pd
d = {
'price_one': 12,
'price_two': 13,
'price_three': 5
}
df = pd.DataFrame(list(d.values()), columns=['val'], index=d.keys())
df.loc['price_one'] = 1
df.sort_values(['val'])
Outputs:
1
Pulling inpandas
(and incredibly heavyweight framework) for this seems a bit much. It's fine if you're usingpandas
anyway, but I wouldn't use it as a go-to solution in general.
– ShadowRanger
Jan 3 at 1:55
add a comment |
You mentioned Python in general. You could use a dataframe:
import pandas as pd
d = {
'price_one': 12,
'price_two': 13,
'price_three': 5
}
df = pd.DataFrame(list(d.values()), columns=['val'], index=d.keys())
df.loc['price_one'] = 1
df.sort_values(['val'])
Outputs:
1
Pulling inpandas
(and incredibly heavyweight framework) for this seems a bit much. It's fine if you're usingpandas
anyway, but I wouldn't use it as a go-to solution in general.
– ShadowRanger
Jan 3 at 1:55
add a comment |
You mentioned Python in general. You could use a dataframe:
import pandas as pd
d = {
'price_one': 12,
'price_two': 13,
'price_three': 5
}
df = pd.DataFrame(list(d.values()), columns=['val'], index=d.keys())
df.loc['price_one'] = 1
df.sort_values(['val'])
Outputs:
You mentioned Python in general. You could use a dataframe:
import pandas as pd
d = {
'price_one': 12,
'price_two': 13,
'price_three': 5
}
df = pd.DataFrame(list(d.values()), columns=['val'], index=d.keys())
df.loc['price_one'] = 1
df.sort_values(['val'])
Outputs:
answered Jan 3 at 0:45
deckarddeckard
31527
31527
1
Pulling inpandas
(and incredibly heavyweight framework) for this seems a bit much. It's fine if you're usingpandas
anyway, but I wouldn't use it as a go-to solution in general.
– ShadowRanger
Jan 3 at 1:55
add a comment |
1
Pulling inpandas
(and incredibly heavyweight framework) for this seems a bit much. It's fine if you're usingpandas
anyway, but I wouldn't use it as a go-to solution in general.
– ShadowRanger
Jan 3 at 1:55
1
1
Pulling in
pandas
(and incredibly heavyweight framework) for this seems a bit much. It's fine if you're using pandas
anyway, but I wouldn't use it as a go-to solution in general.– ShadowRanger
Jan 3 at 1:55
Pulling in
pandas
(and incredibly heavyweight framework) for this seems a bit much. It's fine if you're using pandas
anyway, but I wouldn't use it as a go-to solution in general.– ShadowRanger
Jan 3 at 1:55
add a comment |
Try this:
d = {
'price_one': 12,
'price_two': 13,
'price_three': 5
}
def get_sorted(d):
sorted_list = sorted(list(d.values()))
return tuple(zip(sorted_list, d[key] for key in sorted_list))
# end get_sorted
print(get_sorted(d))
d['price_one'] = 1
print(get_sorted(d))
Note that you would have to call get_sorted(d)
each time...
Also, it returns a tuple of pairs (key, value) sorted with their keys. If you wanted to access say the 3rd value, do get_sorted(d)[2][1]
. The 2
for the third pair, the 1
for the value.
I'm pretty sure this won't work. When this line is executedd['price_one'] = 1
, the value will not change in the list
– bpgeck
Jan 3 at 0:21
I've changed it so it's a function instead. It might not be pretty but it works.
– GeeTransit
Jan 3 at 0:22
Gotcha thanks for the changes
– bpgeck
Jan 3 at 0:29
No problem. If it works, you can help other programmers like you get this answer when they see this question by pressing the checkmark to mark it as a correct answer. Keep up the great work :D
– GeeTransit
Jan 3 at 0:32
add a comment |
Try this:
d = {
'price_one': 12,
'price_two': 13,
'price_three': 5
}
def get_sorted(d):
sorted_list = sorted(list(d.values()))
return tuple(zip(sorted_list, d[key] for key in sorted_list))
# end get_sorted
print(get_sorted(d))
d['price_one'] = 1
print(get_sorted(d))
Note that you would have to call get_sorted(d)
each time...
Also, it returns a tuple of pairs (key, value) sorted with their keys. If you wanted to access say the 3rd value, do get_sorted(d)[2][1]
. The 2
for the third pair, the 1
for the value.
I'm pretty sure this won't work. When this line is executedd['price_one'] = 1
, the value will not change in the list
– bpgeck
Jan 3 at 0:21
I've changed it so it's a function instead. It might not be pretty but it works.
– GeeTransit
Jan 3 at 0:22
Gotcha thanks for the changes
– bpgeck
Jan 3 at 0:29
No problem. If it works, you can help other programmers like you get this answer when they see this question by pressing the checkmark to mark it as a correct answer. Keep up the great work :D
– GeeTransit
Jan 3 at 0:32
add a comment |
Try this:
d = {
'price_one': 12,
'price_two': 13,
'price_three': 5
}
def get_sorted(d):
sorted_list = sorted(list(d.values()))
return tuple(zip(sorted_list, d[key] for key in sorted_list))
# end get_sorted
print(get_sorted(d))
d['price_one'] = 1
print(get_sorted(d))
Note that you would have to call get_sorted(d)
each time...
Also, it returns a tuple of pairs (key, value) sorted with their keys. If you wanted to access say the 3rd value, do get_sorted(d)[2][1]
. The 2
for the third pair, the 1
for the value.
Try this:
d = {
'price_one': 12,
'price_two': 13,
'price_three': 5
}
def get_sorted(d):
sorted_list = sorted(list(d.values()))
return tuple(zip(sorted_list, d[key] for key in sorted_list))
# end get_sorted
print(get_sorted(d))
d['price_one'] = 1
print(get_sorted(d))
Note that you would have to call get_sorted(d)
each time...
Also, it returns a tuple of pairs (key, value) sorted with their keys. If you wanted to access say the 3rd value, do get_sorted(d)[2][1]
. The 2
for the third pair, the 1
for the value.
edited Jan 3 at 0:21
answered Jan 3 at 0:18
GeeTransitGeeTransit
694316
694316
I'm pretty sure this won't work. When this line is executedd['price_one'] = 1
, the value will not change in the list
– bpgeck
Jan 3 at 0:21
I've changed it so it's a function instead. It might not be pretty but it works.
– GeeTransit
Jan 3 at 0:22
Gotcha thanks for the changes
– bpgeck
Jan 3 at 0:29
No problem. If it works, you can help other programmers like you get this answer when they see this question by pressing the checkmark to mark it as a correct answer. Keep up the great work :D
– GeeTransit
Jan 3 at 0:32
add a comment |
I'm pretty sure this won't work. When this line is executedd['price_one'] = 1
, the value will not change in the list
– bpgeck
Jan 3 at 0:21
I've changed it so it's a function instead. It might not be pretty but it works.
– GeeTransit
Jan 3 at 0:22
Gotcha thanks for the changes
– bpgeck
Jan 3 at 0:29
No problem. If it works, you can help other programmers like you get this answer when they see this question by pressing the checkmark to mark it as a correct answer. Keep up the great work :D
– GeeTransit
Jan 3 at 0:32
I'm pretty sure this won't work. When this line is executed
d['price_one'] = 1
, the value will not change in the list– bpgeck
Jan 3 at 0:21
I'm pretty sure this won't work. When this line is executed
d['price_one'] = 1
, the value will not change in the list– bpgeck
Jan 3 at 0:21
I've changed it so it's a function instead. It might not be pretty but it works.
– GeeTransit
Jan 3 at 0:22
I've changed it so it's a function instead. It might not be pretty but it works.
– GeeTransit
Jan 3 at 0:22
Gotcha thanks for the changes
– bpgeck
Jan 3 at 0:29
Gotcha thanks for the changes
– bpgeck
Jan 3 at 0:29
No problem. If it works, you can help other programmers like you get this answer when they see this question by pressing the checkmark to mark it as a correct answer. Keep up the great work :D
– GeeTransit
Jan 3 at 0:32
No problem. If it works, you can help other programmers like you get this answer when they see this question by pressing the checkmark to mark it as a correct answer. Keep up the great work :D
– GeeTransit
Jan 3 at 0:32
add a comment |
The dictionary keys are references to particular entries in a dictionary.
A function to generate a list of dictionary keys in the order of the dictionary entry values is:
def sorted_keys(d):
return sorted(d.keys(), key=lambda k: d[k])
so to access the smallest price in your example:
ks = sorted_keys(d)
smallest = d[ ks[0] ]
The problem is that you have to recalculate your ordering on any insert, change or delete of the dictionary. These would be hard to intercept so better to keep control and recalculate the ordering just when you want to use it.
You could bury all this in a class SortedDict(dict)
that overrides the get function of a dictionary.
add a comment |
The dictionary keys are references to particular entries in a dictionary.
A function to generate a list of dictionary keys in the order of the dictionary entry values is:
def sorted_keys(d):
return sorted(d.keys(), key=lambda k: d[k])
so to access the smallest price in your example:
ks = sorted_keys(d)
smallest = d[ ks[0] ]
The problem is that you have to recalculate your ordering on any insert, change or delete of the dictionary. These would be hard to intercept so better to keep control and recalculate the ordering just when you want to use it.
You could bury all this in a class SortedDict(dict)
that overrides the get function of a dictionary.
add a comment |
The dictionary keys are references to particular entries in a dictionary.
A function to generate a list of dictionary keys in the order of the dictionary entry values is:
def sorted_keys(d):
return sorted(d.keys(), key=lambda k: d[k])
so to access the smallest price in your example:
ks = sorted_keys(d)
smallest = d[ ks[0] ]
The problem is that you have to recalculate your ordering on any insert, change or delete of the dictionary. These would be hard to intercept so better to keep control and recalculate the ordering just when you want to use it.
You could bury all this in a class SortedDict(dict)
that overrides the get function of a dictionary.
The dictionary keys are references to particular entries in a dictionary.
A function to generate a list of dictionary keys in the order of the dictionary entry values is:
def sorted_keys(d):
return sorted(d.keys(), key=lambda k: d[k])
so to access the smallest price in your example:
ks = sorted_keys(d)
smallest = d[ ks[0] ]
The problem is that you have to recalculate your ordering on any insert, change or delete of the dictionary. These would be hard to intercept so better to keep control and recalculate the ordering just when you want to use it.
You could bury all this in a class SortedDict(dict)
that overrides the get function of a dictionary.
answered Jan 3 at 1:23
Mike RobinsMike Robins
1,315511
1,315511
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%2f54014800%2flist-of-references-to-items-in-a-dictionary%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
1
Not sure what the actual use case is here, but would it be solved by
OrderedDict
? docs.python.org/3/library/…– JacobIRR
Jan 3 at 0:11
@JacobIRR Interesting. It looks like this could work for me. If I were to change a value in the dictionary, would the order also change?
– bpgeck
Jan 3 at 0:15
1
OrderedDict (and normal dict on python 3.7+ / ipython 3.6+) are insert ordered - the only way to keep them ordered is to create them a-new:
d =dict(d.items())
after changing something - which is not really good. Why do you need this and whatfor - how big is the dict? Why not create adef get_ordered_items(d): return sorted(d.values())
funciton?– Patrick Artner
Jan 3 at 0:21
@PatrickArtner It seems likes I need to resort after every modification anyway so this may be the best option
– bpgeck
Jan 3 at 0:29
1
Are you trying to efficiently maintain a sorted container? Because then you should just use sorted containers
– juanpa.arrivillaga
Jan 3 at 2:33