Durga
Durga

Reputation: 137

Accessing dictionary elements and concatenating with String and print

I have started learning python. In this code, I am trying to print the Birthdate of the inputted user along with his/her name. I am using a dictionary to achieve this functionality. Below is my code snippet

n=input("Enter Name: ")
    def birth():
        dict1={{"name":"X","birthdate":"16-June-1989"},{"name":"Y","birthdate":"23-08-1990"}}
        if dict1["name"]==n:
            print(dict1["name"]+"'s birth was on " +dict1["birthdate"])
        else:
            print("Not in database")
    birth()

My expected output should look like this on inputting X:

X's birthdate was on 16-June-1989

But I am getting below error, I tried an online search, but I wanted to understand what I am missing here. I am sure I will be getting many comments. But I am also sure that many will provide constructively and learning suggestions.

  File "main.py", line 8, in <module>                                                                                   
    birth()                                                                                                             
  File "main.py", line 3, in birth                                                                                      
    dict1={{"name":"X","birthdate":"16-June-1989"},{"name":"Y","birthdate":"23-08-1990"}}                               
TypeError: unhashable type: 'dict'

Upvotes: 0

Views: 213

Answers (4)

Subash
Subash

Reputation: 895

You are getting the error because dictionary variable dict1 can't parse its own elements,so you need to create an variable/object which can parse the elements of the dictionary which is done by parse variable p

n=input("Enter name: ")
def birth(n):  
        dict1=[{"name":"X","birthdate":"16-June-1989"},{"name":"Y","birthdate":"23-08-1990"}] 
        for p in dict1: 
            if p["name"]==n: 
               print(p["name"]+"'s birth was on " +p["birthdate"])
               break;
            else: 
                print("Not in database")
                break;
birth(n)

Upvotes: 1

Kyrylo Kundik
Kyrylo Kundik

Reputation: 64

That's because you have a wrong dict initialization. In python 3+ curly brackets are used not only for dict literal but and for set literal. You can get more info in this question.

For example:

# that will be a dict:
d = {"name": "My name", "birthdate": "16-June-1989"}

# and that will be a set:
d = {"name", "birthdate"}

# your line 3 has set initialization, which contains 2 dicts of user info:
dict1={{"name":"X","birthdate":"16-June-1989"},{"name":"Y","birthdate":"23-08-1990"}}

One more problem that in Python sets must contain only hashable elements and dict is not hashable. Here is the explanation.

So you should change your dict1 variable type to list or tuple. If you need more info about the difference between lists, sets and tuples here is a link to python documentation about data structures.

And also your function will print something for every entry in your database. I think that you need only 1 print after function execution.

So your function should look like that:

def birth(name):
    database = [{"name": "X", "birthdate": "16-June-1989"},
                {"name": "Y", "birthdate": "23-08-1990"}]
    found = False
    for entry in database:
        if entry["name"] == name:
            print(entry["name"] + "'s birth was on " + entry["birthdate"])
            found = True
            break
    if not found:
        print("Not in database")


birth('X')
# Will print: X's birth was on 16-June-1989
birth('My name is')
# Will print: Not in database

Upvotes: 1

Mr-Pepe
Mr-Pepe

Reputation: 87

Make sure that your dictionary definition is correct. It should have the form:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}

You can not use a dictionary as a key in a dictionary.

From the Python documentation:

dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().

Upvotes: 0

Mayank Porwal
Mayank Porwal

Reputation: 34056

The way you defined your dict1 is incorrect. It should be like this:

In [1131]: def birth(n): 
      ...:         #dict1={{"name":"X","birthdate":"16-June-1989"},{"name":"Y","birthdate":"23-08-1990"}} 
      ...:         dict1=[{"name":"X","birthdate":"16-June-1989"},{"name":"Y","birthdate":"23-08-1990"}] 
      ...:         for d in dict1: 
      ...:             if d["name"]==n: 
      ...:                 print(d["name"]+"'s birth was on " +d["birthdate"]) 
      ...:             else: 
      ...:                 print("Not in database") 
      ...:                                                                                                                                                                                                  

In [1132]: birth(n)                                                                                                                                                                                         
X's birth was on 16-June-1989

Also, it would make more sense if you pass the user input n as a parameter to your function birth. Then call the method like birth(n).

Otherwise, the method is tightly coupled with the variable named n.

Upvotes: 1

Related Questions