简体   繁体   中英

how to show both key and value in dictionary in the format they are in

I have a dictionary look like this

mydict = { 'type': 'fruit', 'quantity': 20 }

i wan to print only the 'type' field in the way it is,like this {'type': 'fruit'}

i found this on other website

class fruits(dict):
    def __str__(self):
        return json.dumps(self)
collect = [['apple','grapes']]
result = fruits(collect)
print(result)

is there a simpler way without jsonify it? i also tried.items() method but it print out as (key, value) which i dont wan it to be

If you're trying to define a class that behaves exactly like dict with the only exception being that it always prints in a particular way, this might be the way to go:

class subclass_of_dict(dict):
    def __str__(self):
        return "{'type' : " + f"'{self.get('type')}'" + '}'

With your class defined like this, you can now create a couple of instances of this new class:

f1 = subclass_of_dict({'type' : 'fruit', 'quantity': 20})
f2 = subclass_of_dict({'type' : 'bowler hats', 'quantity': 13})

Then calling print on these instances does this:

print (f1)
print (f2)

# result: 
    # {'type' : 'fruit'}
    # {'type' : 'bowler hats'}

Is this what you're after?

This one is very easy. You have to write only few lines of code.

class fruits(dict):
def __str__(self):
    return "{'type' : " + f"'{self.get('type')}'" + '}'

Then you have to just make your dictionary and print.

mydict = fruits{ 'type' : 'fruit', 'quantity': 20 }
print(mydict)

I guess you've found your answer. To learn more about a dictionary in an easy way, follow Python Dictionary .

Hope this comment is helpful for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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