Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

python - comparing order of values of two dictionaries with the same keys

I have two dictionaries - actual labels that stores actual labels of each node in a graph and predicted labels that stores predicted labels of each node in a graph. Both of them contain the same keys but different values associated with each key. Keys in the dictionary are unordered. My question is that if we use the dict.values() function on both the dictionaries, can we be sure that the array of values obtained for both the dictionaries will be of the same order. For example, the first value in actual and predicted array will correspond to the same node label and so on.

question from:https://stackoverflow.com/questions/65853550/comparing-order-of-values-of-two-dictionaries-with-the-same-keys

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In general no. Since Python 3.7 the order is determined by the order of key insertion. So only if the two dictionaries had the same order of key insertion would this be true.

However, you can easily use list comprehensions to create corresponding lists.

Code

# actual - name of actual dictionary
# predicted - name of predicted dictionary
# We create two lists which are in sync as (works since we are constructing
# both list based upon ther order keys in dictionary actual
actual_values = [v for _, v in actual.items()]
predicted_values = [predicted[k] for k, _ in actual.items()]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...