Python - Printing String of Key in a Dict

python dictionary
python dict to string
python dict values to string
python immutable dict to string
python string representation of a dict
python print dictionary keys
python convert all values in dictionary to string
how to convert list of dictionary to string in python

My code is the following,

prices = {'banana':'4', 'apple':'2', 'orange':'1.5', 'pear':'3'}
stock = {'banana':6, 'apple':0, 'orange':32, 'pear':15}

print("price :" + str(prices.values))
print("stock :" + str(stock.values))

I don't understand why I'm getting a spit out that looks as if I asked for the type. What gives?

Actually, my code logic is wrong.

I want the code to spit out the following

key price : values stock : values

For Example, this is how it should look

apple price: 2 stock: 0

prices = {'banana':'4', 'apple':'2', 'pear':'3'}
stock = {'banana':6, 'orange':32, 'pear':15}
for item in (prices.keys() & stock.keys()):
    print (item,"price:",prices.get(item,'-'),"stock:",stock.get(item,0))


orange price: - stock: 32
pear price: 3 stock: 15
banana price: 4 stock: 6
apple price: 2 stock: 0

Using get with a default will help if the stock and prices dictionaries contain different friuts ('keys') in each. The .get() function really helps here.

As mentioned by mgilson the following line is where the full set of fruit is created.

prices.keys() & stock.keys()  #{'orange', 'pear', 'banana', 'apple'}

I've also done this using set before


But I prefer the & approach.

Python, Python | Convert dictionary object into string Let's see the different ways of changing dictionary into string. print original dictionary Python | Convert key-​value pair comma separated string into dictionary · Python | Ways to convert string to  Print a dictionary line by line using for loop & dict.items() dict.items() returns an iterable view object of the dictionary that we can use to iterate over the contents of the dictionary, i.e. key-value pairs in the dictionary and print them line by line i.e.

You need to call the methods to get anything useful:

print (prices.keys())

However, in python3.x, this still isn't particularly nice for printing since it'll print extra junk that you probably don't want to see.

You might want to consider using str.join on the object returned from dict.keys() or dict.values():

print (' '.join(prices.keys()))

str.join does pretty much what you'd expect it to. The string on the left is the delimiter that gets inserted between each element in the iterable you pass to join. For example:


will result in the string: "foo!bar!baz". The only gotcha here is that each element in the iterable that you pass to str.join must be a string.

As for your edit,

prices = {'banana':'4', 'apple':'2', 'orange':'1.5', 'pear':'3'}
stock = {'banana':6, 'apple':0, 'orange':32, 'pear':15}
prices.keys() & stock.keys()  #{'orange', 'pear', 'banana', 'apple'}
for item in (prices.keys() & stock.keys()):
    print (item,"price:",prices[item],"stock:",stock[item])

which outputs:

orange price: 1.5 stock: 32
pear price: 3 stock: 15
banana price: 4 stock: 6
apple price: 2 stock: 0

seems like it is what you want.

How to convert dictionary keys and values to strings in Python, How to convert dictionary keys and values to strings in Python. A key is new_d = {str(key): str(value) for key, value in keys_values}. print(new_d). Output. Python print dictionary keys and values : In this tutorial, we will learn how to print the keys and values of a dictionary in python. For printing the keys and values, we can either iterate through the dictionary one by one and print all key-value pairs or we can print all keys or values at one go.

The top two answers recommend using .keys(), but note that this returns an object of type dict_keys, not an index-able object like a list of strings. To get a list of the keys as strings, you should simply cast the dictionary as a list: list(my_dict).

>>> prices = {'banana':'4', 'apple':'2', 'pear':'3'}
>>> print(prices.keys())
dict_keys(['banana', 'apple', 'pear'])
>>> prices.keys()[2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'dict_keys' object does not support indexing
>>> print(list(prices))
['banana', 'apple', 'pear']
>>> list(prices)[2]

Python: 4 ways to print items of a dictionary line by line – thispointer , Iterate over the keys in dictionary, access value & print line by line dictionary in json.dumps() to get a string that contains each key-value pair  Python | Extract specific keys from dictionary We have a lot of variations and applications of dictionary container in Python and sometimes, we wish to perform a filter of keys in dictionary, i.e extracting just the keys which are present in particular container.

Since both dictionaries/objects have the same keys you can use a simple for loop to iterate over one of the dictionaries and print the price and stock of each item.

prices = {"banana": 4, "apple": 2, "orange": 1.5, "pear": 3}
stock  = {"banana": 6, "apple": 0, "orange": 32, "pear": 15}
for key in prices:
    print "stock: %s" % stock[key]
    print "prices: %s" % prices[key]

Python Dictionaries, for city in sorted(temps): print city London Madrid Oslo Paris. Python also has a special dictionary type OrderedDict where the key-value pairs has a specific  How to convert string to date in python with different algorithms ? 18 hours ago How to do proper formatting of XML differences in dictionary using python 3.4.4 2 days ago All categories

prices = {"banana": 4, "apple": 2, "orange": 1.5, "pear": 3}
stock  = {"banana": 6, "apple": 0, "orange": 32, "pear": 15}
for key in prices:
    print key
    print "stock: %s" % stock[key]
    print "prices: %s" % prices[key]

which outputs:

stock: 32
prices: 1.5
stock: 15
prices: 3
stock: 6
prices: 4
stock: 0
prices: 2
=> None

Dictionaries and strings, Python dictionary method str() produces a printable string representation of a #!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7}; print "Equivalent String : %s"  Python dictionary method keys() returns a list of all the available keys in the dictionary. Syntax. Following is the syntax for keys() method − dict.keys() Parameters. NA. Return Value. This method returns a list of all the available keys in the dictionary. Example. The following example shows the usage of keys() method.

Python dictionary str() Method, They are Python's built-in mapping type. They map For this dictionary, the keys are strings. We can print the current value of the dictionary in the usual way:. Python – Concatenate Dictionary string values Sometimes, while working with dictionaries, we might have utility problem in which we need to perform elementary operation among the common keys of dictionaries.

20. Dictionaries, Python's built-in sorted function returns a list of a dictionaries keys in sorted order: which is a string, to a variable named contents , and finally print contents to  The initialiser for dict/OrderedDict objects requires an interable of pairs key, val. As you clearly show in your testing, sorted(a) is an iterable but not of pairs, hence ValueError: need more than 1 value to unpack. If you want to create a dictionary from sorted(a), you should do it .fromkeys:

6. Dictionaries, sets, files, and modules, If we print the dictionary again, we see a key-value pair with a colon between the key For dictionaries, Python uses an algorithm called a hash table that has a Suppose you are given a string and you want to count how many times each  In this tutorial, learn how to get dictionary value by key in Python. If you want to find the value of a known key, you have to use the Python get() function. The dictionary contains the keys with its associated values. The values in the dictionary variable can be identified by the key.

  • Why does the orange price not come up but the apple does?
  • Ah, nevermind, I just used | instead of & and got my desired result. Thank you again!
  • Thank you. I'm not familiar with join. I'll look it up now.
  • thank you but even with the fix, the code is not doing what I thought it would. Could you take a look at my edit?
  • @algebr -- I saw you edit. I'm not sure that I understand what you expect the output to be. Could you clarify the post showing exactly what you want the output to be?
  • Awesome! thank you so much again. but line 3 of your code, what does it do? it just seems like its floating..?
  • @algebr -- It is floating. I put it there to demonstrate what dict1.keys() & dict2.keys() does. In this case, it really does pretty much the same thing as dict1.keys() since your dictionarys have the same keys -- If they didn't, it would return the intersection of the two sets of keys.