所以我有一个带有值的字典:[假设不重复]
require(corrplot)
#Reorder data collected in mtcars in this way:
mtcars2 <- mtcars[ , c("carb", "wt", "hp", "cyl", "disp",
"qsec", "vs",
"mpg", "drat", "am", "gear")
]
#Let's say I have the following groups corresponding to these variables
groups <- c("","Engine",rep("", 3), "Speed","", "Fuel",rep("", 3) )
rows <- c("Engine","",rep("", 3), "Speed","", "Fuel",rep("", 3) )
R <- cor(mtcars2)
colnames(R) <- groups
rownames(R) <- rows
corrplot(R, diag = FALSE, method = "ellipse", type = "upper", tl.col = "black")
我想做的就是使用值获取他们的键,所以如果给定1,我希望它获取具有值1(即0)并将其附加到列表中的键。
mydict={0: 1, 1: 2, -2: -1, -1: 0, -3: -2}
我不想创建for循环,因为我想在线性时间内完成。
答案 0 :(得分:2)
如果可以确保您的值唯一,则可以创建dict
的反向版本,在其中切换键和值:
mydict = {0: 1, 1: 2, -2: -1, -1: 0, -3: -2}
my_inverted_dict = dict(map(reversed, mydict.items()))
print(my_inverted_dict)
print(my_inverted_dict[1])
输出:
{1: 0, 2: 1, -1: -2, 0: -1, -2: -3}
0
答案 1 :(得分:1)
您将为此循环,因为您必须反转字典的映射。为此,您可以使用字典理解:
Get-Content $alertlog|select-string $(Get-Date -format "ddd MMM dd") -Context 0,1
答案 2 :(得分:1)
mydict={0: 1, 1: 2, -2: -1, -1: 0, -3: -2}
search_value = 1
# List comprehension to return items if they match a search value
# This populates a list automatically
final0 = [k for k, v in mydict.items() if v == search_value]
# Note: If you have a value that is paired with more than one key
# then you might want to use set() and iterate through that to ensure
# your values aren't duplicates.
mydict2 = {0: 1, 1: 2, -2: -1, -1: 0, -3: -2, 4: 1} # Added matching value at end
final0 = [i for i in set([k for k, v in mydict.items() if v == search_value])]