my_dict = dict([(1,'apple'), (2,'ball')])
when I print my_dict the output is
{1: 'apple', 2: 'ball'}
How it's working?
I am new to python Please explain this
Thanks in advance!
Dictionary is data structure in Python. Think about it as an unordered(after python3.7 can be ordered) set of key: value pairs.
The values of a dictionary can be of any type, keys must be of an immutable data type such as strings, numbers, or tuples.
In your command, dict() used as constructor and values([(1,'apple'), (2,'ball')]) is an iterable object.
Each item in the iterable is itself an iterable with exactly two objects. The first object of each item becomes a key in the new dictionary, and the second object the corresponding value.
Here is different representation of your example:
list_of_tuples = [(1,'apple'), (2,'ball')]
in order to create a dictionary, program will need to iterate thru the each value in the list_of_tuples
thats why you can use dict() constructor to do it, like so:
my_dict = dict(list_of_tuples)
Note that if a key occurs more than once, the last value for that key becomes the corresponding value in the new dictionary.
When you create a dictionary you do with curly brackets, {}, with the keys and values separated by colons, :. Here's an example
my_dict = {
1 : 'apple',
2 : 'ball'
}
You can index this dictionary with square brackets as you've done in the question.
When you call print on this dictionary it prints it out in a similar fashion with the key followed a colon and the value, all encompassed within curly brackets.
{1: 'apple', 2: 'ball'}
If you would like to print a particular value in the dictionary you do so as follows
print my_dict[1]
This would print out the value associated with 1 in the dictionary which in our example is
apple
Related
Hello I am trying to figure out how to perform an lstrip on each value of a dictionary when the value is a list. Lets call the name of the dictionary test.
This is an example of one key-value pair in the dictionary test. There are 100+ key-value pairs.
'names: ['10jack',
'300alex',
'200michael',
'105mike',
'234joe',
'50robert']'
I tried the following and it wasn't working since the value of the dictionary was a list. I am trying to remove the numbers in front of each name.
clean_dict = {key: item.lstrip('0123456789.- ') for key, item in test.items()}
Use a list comprehension to iterate over all the list elements.
clean_dict = {key.strip(): [el.lstrip('0123456789.- ') for el in value] for key, value in test.items()}
I am unpacking a nested dictionary that I get from an API so I have no control over it. One of the sub dictionaries comes out as <class 'list'> in the form {'A':'B', 'C':'D', etc}. How can I convert this into a dictionary where the item on the left of the colon is the key and the item on the right is the value? I'm using python 3 if that helps.
def print_nested(dict_obj):
# Iterate over all key-value pairs of a dict
for key, value in dict_obj.items():
if isinstance(value, dict):
print_nested(value)
else:
if isinstance(value, list):
print(type(value))
print(*value)
else:
print(key, ':', value)
produces output:
<class 'list'>
{'putCall': 'CALL', 'symbol': 'MSFT_031723C250', etc}
The output from your code is consistent with there being a top-level dictionary that maps some unknown key to a list, which in its turn contains another dictionary.
You're being a bit mislead about the list contents because you're calling print(*value), which is unpacking the list items into separate arguments to print. If you just did print(value) (without the *), you'd see the square brackets you'd expect from a list. It may be that your list contains only one item, but it's also possible that if it contains several large dictionaries the end of one and the start of the next may be hard to spot in the output.
I'm not sure what output you want if you had a structure like {"foo": [{"bar": 1}]}. Do you just want the inner most keys and values printed?
Then you probably want your list handling branch to be something like this (though you might need more logic if there might be lists that don't contain only dictionaries):
if isinstance(value, list):
for inner in value:
print_nested(inner)
i have a a way for concerting the list and set , to the dict:
you know that if you do the below activation , you would have error:
PSR=["hello","bye"]
PSR=dict(PSR)
print(PSR)
now , i want to show you a module to solve your problems:
we have module to name dict.fromkeys(list or set , value of keys), i made an example:
PSR=["hello","bye"]
#our primitive/first list
behave="good"
#the value of the keys
PSR=dict.fromkeys(PSR,behave)
print(PSR)
#you will have a dict!
i have below list, trying to pull the value of the list pair, example i need to know what is the average_buy_price from the list.
[{'enabled': True, 'total_buy_quantity': 45, 'average_buy_price': '6755.03'}]
currently it is giving error.
TypeError: list indices must be integers or slices, not str
the above output is coming from system, i need to select only the value which i need. example ( 'average_buy_price') need to get the output of the value. '6755.03
one thing i have notice is that, it is starting with [ and closing with ] , for testing i just copied from { to } i am able to pull the value, looks like some problem with syntax when i am using. required help.
In you list there is a single dictionary. To access average_buy_price from the dict try:
test_list = [{'enabled': True, 'total_buy_quantity': 45, 'average_buy_price': '6755.03'}]
print(test_list[0].get('average_buy_price')) # output 6755.03
Yes, as long as you have the square brackets, it's a list, and so it cannot be indexed with a string.
Get rid of the square brackets (and retain only the curly braces). It is then no longer a list, but a dictionary, which can be indexed with the string key value.
Each element of your list is actually a dictionary. So, iterate through the list, then get the key, value pair.
myList= [{'enabled': True, 'total_buy_quantity': 45, 'average_buy_price': '6755.03'}]
for d in myList:
for k, v in d.items():
print(k,': ',v)
Output:
enabled : True
total_buy_quantity : 45
average_buy_price : 6755.03
You have a list containing a single dictionary. If you want to access the elements of the dictionary, first index the list: test_list[0]['average_buy_price']
I have a list which is composed of tuples where the employee is unique:
my_list = [(Decimal('679.666666'), 'Employee1'),
(Decimal('792.000000'), 'Employee2'),...]
and I've made it to dictionary by using:
new_dict = dict(my_list)
However, I found the size of the object has been reduced after it is converted to dictionary (len(my_list) = 404, len(new_dict) = 353)
I have no idea why this is happening. Can anyone let me know what is wrong?
Many thanks.
When you convert a list of tuples to a dictionary, the first value of the tuple is taken as the key in the dictionary, and the second value as the value.
Most probably there are tuples where the first value is equal to the first value of some other tuples, and hence in those cases the values get overwritten by the tuples that come later. And hence this would be the reason why the dictionary size is lesser than the list size.
Example to show this -
>>> l = [(1,2),(2,3),(1,4)]
>>> dict(l)
{1: 4, 2: 3}
I have the following string :
str = "{application.root.category.id:2}"
I would like to convert the above to a dictionary data type in python as in :
dict = {application.root.category.id:2}
I tried using eval() and this is the error I got:
AttributeError: java package 'application' has no attribute "root"
My current python is of <2.3 and I cannot update the python to >2.3 .
Any solutions ?
Python dictionaries have keys that needn't be strings; therefore, when you write {a: b} you need the quotation marks around a if it's meant to be a string. ({1:2}, for instance, maps the integer 1 to the integer 2.)
So you can't just pass something of the sort you have to eval. You'll need to parse it yourself. (Or, if it happens to be easier, change whatever generates it to put quotation marks around the keys.)
Exactly how to parse it depends on what your dictionaries might actually look like; for instance, can the values themselves be dictionaries, or are they always numbers, or what? Here's a simple and probably too crude approach:
contents = str[1:-1] # strip off leading { and trailing }
items = contents.split(',') # each individual item looks like key:value
pairs = [item.split(':',1) for item in items] # ("key","value"), both strings
d = dict((k,eval(v)) for (k,v) in pairs) # evaluate values but not strings
First, 'dict' is the type name so not good for the variable name.
The following, does precisely as you asked...
a_dict = dict([str.strip('{}').split(":"),])
But if, as I expect, you want to add more mappings to the dictionary, a different approach is required.
Suppose I have a string
str='{1:0,2:3,3:4}'
str=str.split('{}')
mydict={}
for every in str1.split(','):
z=every.split(':')
z1=[]
for every in z:
z1.append(int(every))
for k in z1:
mydict[z1[0]]=z1[1]
output:
mydict
{1: 0, 2: 1, 3: 4}