简体   繁体   English

如果值匹配,如何打印字典的键?

[英]How can I print the keys of a dictionary if a value matches?

I have made a dictionary which you can see below,我做了一本字典,你可以在下面看到,

dic1={'T1':{'ID':101,'Salary':20000,'ML':15,'DL':10,'CL':12,'P1':'8th','P2':'9th','P3':'10th','FP':4},
'T2':{'ID':102,'Salary':15000,'ML':15,'DL':10,'CL':12,'P4':'10th','P5':'7th','P6':'12th','FP':2},
'T3':{'ID':103,'Salary':15000,'ML':15,'DL':10,'CL':12,'P7':'5th','P8':'10th','P2':'12th','FP':1},
'T4':{'ID':104,'Salary':15000,'ML':15,'DL':10,'CL':12,'P4':'4th','P6':'9th','P1':'10th','FP':3}}

here I want to take user's input that which teacher is absent and then apply a loop which sees the periods(P1,P2 etc) stored in the details of teacher who is absent, then print the key(another teachers(T1,T2 etc)) which have the periods of absent teacher in their free period.在这里,我想获取用户输入的哪个老师缺席,然后应用一个循环,该循环查看存储在缺席老师详细信息中的句点(P1、P2 等),然后打印密钥(另一位老师(T1、T2 等) ) 在他们的空闲时间里有老师缺席的时间。

For referrence: Imagine teacher T1 is absent which have period 1,2,3(P1,P2,P3) respectively in classes.供参考:假设T1老师缺席,班级分别有1,2,3(P1,P2,P3)期。 Now the loop prints the teachers who have period 1,2,3 in their free period(FP) respectively(ie T2,T3,T4)现在循环分别打印在空闲时间 (FP) 中有时间 1、2、3 的教师(即 T2、T3、T4)

I have tried using different loops(one Is Given below) but not getting the output I want that I have told you earlier.我试过使用不同的循环(下面给出了一个循环)但没有得到 output 我想要我之前告诉过你的。 So, please tell me if anyone has any solution or if I have to change anything in the dictionary which might help me in getting the required output.所以,请告诉我是否有人有任何解决方案,或者我是否必须更改字典中的任何内容,这可能有助于我获得所需的 output。

a=input("Enter Teacher name")
k={key: val for key,val in dic1[a].items() if key.startswith('P')}
for i in dic1:
    for j in dic1[i].items():
        if j==k:
            print(i)
            print(k)
            print(j)
print(i)
print(k)
print(j)

Great question, I'll answer in two parts, the first will address why your example loop is not working.很好的问题,我将分两部分回答,第一部分将解决您的示例循环不起作用的原因。 and the second will provide a working solution (though it may not be particularly well optimised).第二个将提供一个可行的解决方案(尽管它可能没有得到特别好的优化)。

Part 1第1部分

Looking at your example, when you run your loop, j will be a tuple containing a key, value pair from each teacher's data.查看您的示例,当您运行循环时, j将是一个元组,其中包含每个教师数据中的键值对。 When you create k it is a dictionary.当您创建k时,它是一本字典。 If you add a print statement before your if j==k: you will see what j and k are.如果在if j==k:之前添加打印语句,您将看到jk是什么。 Here is an example of the first few j 's and k 's for the first teacher:这是第一位老师的前几个jk的示例:

j = ('ID', 101), k = {'P1': '8th', 'P2': '9th', 'P3': '10th'}
j = ('Salary', 20000), k = {'P1': '8th', 'P2': '9th', 'P3': '10th'}
j = ('ML', 15), k = {'P1': '8th', 'P2': '9th', 'P3': '10th'}
j = ('DL', 10), k = {'P1': '8th', 'P2': '9th', 'P3': '10th'}
j = ('CL', 12), k = {'P1': '8th', 'P2': '9th', 'P3': '10th'}
j = ('P1', '8th'), k = {'P1': '8th', 'P2': '9th', 'P3': '10th'}
j = ('P2', '9th'), k = {'P1': '8th', 'P2': '9th', 'P3': '10th'}
j = ('P3', '10th'), k = {'P1': '8th', 'P2': '9th', 'P3': '10th'}
j = ('FP', 4), k = {'P1': '8th', 'P2': '9th', 'P3': '10th'}

As you can see, even when j = ('FP', 4) , it is a tuple.如您所见,即使j = ('FP', 4) ,它也是一个元组。 When you test for equality by writing if j == k: it will fail as j is a tuple and k is a dict.当您通过编写if j == k:来测试相等性时,它将失败,因为j是一个元组而k是一个字典。 The object type is compared during an equality test so this will fail. object 类型在相等性测试期间进行比较,因此这将失败。 Note: equality tests are very strict so j and k must be exactly equal (type and contents) to return true.注意:相等性测试非常严格,因此 j 和 k 必须完全相等(类型和内容)才能返回 true。

Part 2第2部分

The following code should solve your problem.下面的代码应该可以解决您的问题。 I've added comments to explain it line by line.我添加了注释以逐行解释它。

There are a couple of useful points to note.有几个有用的要点需要注意。

  1. First we create a list of periods the teacher is absent from called target_periods .首先,我们创建一个名为target_periods的教师缺席时段列表。 You'll note that I've replaced 'P' with '' and then cast the result as an integer. This makes sure that the period numbers are formatted the same way as the FP values we will compare to later on.您会注意到,我已将“P”替换为“”,然后将结果转换为 integer。这可确保期间数字的格式与我们稍后将比较的 FP 值的格式相同。
  2. Next when we start looping through the teachers, we need to skip the teacher that's absent.接下来,当我们开始遍历教师时,我们需要跳过缺席的教师。
  3. Finally, as we loop through the remaining teachers, we are only interested in their FP, so we can directly access that by its key and check if its in our list of target periods.最后,当我们遍历剩下的老师时,我们只对他们的 FP 感兴趣,所以我们可以通过它的键直接访问它并检查它是否在我们的目标周期列表中。

Let me know if you need any further clarifications.如果您需要任何进一步的说明,请告诉我。

a=input("Enter Teacher name")

# Get the periods of the absent teacher in a simple list
target_periods = [int(period.replace('P','')) for period in dic1[a].keys() if period.startswith('P')]

for teacher, data in dic1.items():  # Loop through the teachers and their data
    if teacher == a: # Skip the absent teacher
        continue
    elif data['FP'] in target_periods: # Check if the teacher has a period in common with the absent teacher
        print(f'Teacher: {teacher} has period {data["FP"]} in common with {a}')

There's nothing really wrong with your dictionary - it can be used as is.您的词典并没有真正的问题 - 它可以按原样使用。

You first need to check if the teacher specified (input) is in the dictionary.您首先需要检查指定(输入)的老师是否在字典中。 If it is then isolate the Pn keys (their values are irrelevant).如果是,则隔离 Pn 键(它们的值无关紧要)。 Add the numeric part of the Pn keys to a set.将 Pn 键的数字部分添加到一个集合中。

Now iterate over the main dictionary.现在遍历主字典。 Ignore the input teacher.忽略输入老师。 Get the FP value and check if it's in the previously constructed set.获取 FP 值并检查它是否在先前构建的集合中。

Output accordingly: Output 相应地:

dic1 = {'T1': {'ID': 101, 'Salary': 20000, 'ML': 15, 'DL': 10, 'CL': 12, 'P1': '8th', 'P2': '9th', 'P3': '10th', 'FP': 4},
        'T2': {'ID': 102, 'Salary': 15000, 'ML': 15, 'DL': 10, 'CL': 12, 'P4': '10th', 'P5': '7th', 'P6': '12th', 'FP': 2},
        'T3': {'ID': 103, 'Salary': 15000, 'ML': 15, 'DL': 10, 'CL': 12, 'P7': '5th', 'P8': '10th', 'P2': '12th', 'FP': 1},
        'T4': {'ID': 104, 'Salary': 15000, 'ML': 15, 'DL': 10, 'CL': 12, 'P4': '4th', 'P6': '9th', 'P1': '10th', 'FP': 3}}

teacher = input('Enter teacher name: ')

if teacher in dic1:
    p = set()
    for k in dic1[teacher].keys():
        if k.startswith('P'):
            p.add(int(k[1:]))
    for k, v in dic1.items():
        if k != teacher and v.get('FP') in p:
            print(k)
else:
    print('Unknown teacher')

Output: Output:

T2
T3
T4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM