Python 3 - Print Specific List Item from Dictionary - python

I have a dictionary with lists attached to the keys with multiple values inside each list. I'm trying to pull a specific item from the lists of each key. I assumed I could do the following;
for entries in myDictionary:
print("Customer :" + entries[1])
print("Sales Rep:" + entries[2])
print("Item: " + entries[3])
Though that only prints the second, third, and fourth characters of what I assume to be the key itself - it could also be the first list item as I also have the key as the first item within the lists, but I'm going to assume it's the former.
I've read about the following, but I'm unsure how to apply it to my case of wanting to print a specific item from the list. I believe these would print out the entire list per key;
for key, value in my_dict.iteritems():
print key, value
for key in my_dict.iterkeys():
print key
for value in my_dict.itervalues():
print value
Cheers.

Iterating over the dictionary gives you keys; you can always use that key to access the value:
for key in myDictionary:
entries = myDictionary[key]
print("Customer:", entries[1])
print("Sales Rep:", entries[2])
print("Item:", entries[3])
Using dict.values() (or dict.itervalues() or dict.viewvalues() when using Python 2) gives you access to the values instead, which you can then index:
for entries in myDictionary.values():
print("Customer:", entries[1])
print("Sales Rep:", entries[2])
print("Item:", entries[3])
or you can have both the keys and the values with dict.items() (dict.iteritems(), dict.viewitems()):
for key, entries in myDictionary.items():
print("Details for:", key)
print("Customer:", entries[1])
print("Sales Rep:", entries[2])
print("Item:", entries[3])

Related

Why there is multiple values for dictionary key?

I'm watching a python course and I saw a line of code that I don't understand
books_dict[title] = [author,subject,year]
what I see from this line is the key of books_dict is the title and there are multiple values for it?
You can print the type of books_dict[title] with type() function. It tells you that it's a list(so there is only one object). List is a container so it can contain other objects. In your dictionary there is only one value for that key. Whenever you access to that key you will get that one list not individual items inside it. That would be problematic then!
If you have:
d = {}
d["key1"] = [1, 2, 3]
There is only one value, and that value is a list. The list is [author, subject, year].
In addition to what others have already stated, a dictionary holds key, value pairs. One key to one value, however the data types used to create the key and value can both be containers holding more than one element
for example
books_dict[title] = [author,subject,year]
is the same as
temp = [author, subject, year]
books_dict[title] = temp
The key can also hold an iterable, however it must be hashable and immutable.
books_dict[(title, author)] = [subject, year]
which is the same as
key = (title, author)
value = [subject, year]
books_dict[key] = value

dict with one key and multiple values

I was wondering if there's a way for me to pull a value at a specific index. Let's say I have a key with multiple values associated with it. But in my dictionary I have multiple keys, each key with multiple values. I want to iterate through the keys and then each respective value associated with that key. I want to be able to pull the value at the first index and subtract it from the value at the second index.
d= {108572791: [200356.77, 200358], 108577388: [19168.7, 19169]}
output for key 108572791 would be -1.33
output for key 108577388 would be -.03
I've try reading up on dict and how it works apparently you can't really index it. I just wanted to know if there's a way to get around that.
for key, values in total_iteritems():
for value in values:
value[0]-value[1]:
Edit:
Since the question is way different now, I'll address the new subject:
d= {108572791: [200356.77, 200358], 108577388: [19168.7, 19169]}
for i in d:
print("Output for key ",str(i), "would be ",(d[i][1]-d[i][0]))
Output:
Output for key 108572791 would be 1.2300000000104774
Output for key 108577388 would be 0.2999999999992724
Original answer
Yes. When you have a dict containing a list as value if you want to obtain a specific value, then you need to address the index in the list. An example is:
a = {'Name':['John','Max','Robert']}
This means that:
print(a['Name'])
Output:
['John','Max','Robert']
Since ['Name'] is a list:
for i in range(len(a['Name'])):
print(a['Name'][i]
Output:
John #(Because it's the index 0)
Max #(Index = 1)
Robert #(Index = 2)
If you want a specific value (for instance 'Max' which is index = 1)
print(a['Name'][1]
Output:
Max
Depends on how many values in key obvious but this does the trick:
for x in d:
print(x)
print(d[x][0]-d[x][1])
You can use list of tuples if you want to use indexing.
d= [(108572791,[200356.77, 200358]), (108577388,[19168.7, 19169)]
for tuple in my_list:
print(tuple[0])
for value in tuple[1]:
print(value)

Python: print the dictionary elements which has multiple values assigned for each key

I've got a dictionary like the one, below:
{ "amplifier": ["t_audio"],
"airbag": ["t_trigger"],
"trigger": ["t_sensor1", "t_sensor2"],
"hu": ["t_fused"],
"cam": ["t_front", "t_ldw", "t_left", "t_nivi", "t_rear_camera", "t_right"],
"video_screen": ["t_video"] }
as you can see, there are some elements which have more than one value assigned for each key. I'd like to extract those values as string, separately within (preferably) a for loop then print them out. Printed result should be something like this:
group(amplifier, t_audio)
group(airbag, t_trigger)
group(trigger, t_sensor1)
group(trigger, t_sensor2)
group(hu, t_fused)
group(cam, t_front)
group(cam, t_ldw)
...
...
I can easily perform this on a normal dictionary where each key has only one values but got almost confused about this one(sorry if I'm newbe to Python...). Any kind of help is appreciated on how to get this result.
Very simple: loop through each key in the dictionary. Since each value is going to be a list with one or more elements, just loop through those and print the string you need:
d = {'amplifier': ['t_audio'], 'hu': ['t_fused'], 'trigger': ['t_sensor1', 't_sensor2'], 'cam': ['t_front', 't_ldw', 't_left', 't_nivi', 't_rear_camera', 't_right'], 'airbag': ['t_trigger'], 'video_screen': ['t_video']}
for key in d:
for value in d[key]:
print 'group({},{})'.format(key,value)
You can see it in action here: https://eval.in/645071
for key in dict:
for value in dict[key]:
print value
for k, v in mydict.iteritems():
for vv in v:
print "group(%s,%s)" % (k,vv)
#or
print "group(",k,",",vv,")"
#or the python 3 format syntax

Dynamic Python Lists

In the below Python Code, am dynamically create Lists.
g['quest_{0}'.format(random(x))] = []
where random(x) is a random number, how to print the List(get the name of the dynamically created List name?)
To get a list of all the keys of your dictionary :
list(g.keys())
There is nothing different with a regular dictionary because you generate the key dynamically.
Note that you can also put any type of hashable object as a key, such as a tuple :
g[('quest', random(x))] = []
Which will let you get a list of all your quest numbers easily :
[number for tag, number in g.keys() if tag == "quest"]
With this technic, you can actually loop through the tag ('quest'), the number and the value in one loop :
for (tag, number), value in g.items():
# do somthing
Unpacking is your best friend in Python.
You can iterate over the g dictionary with a for loop, like this
for key, value in g.items():
print key, value
This will print all the keys and their corresponding lists.

How can I get dictionary key as variable directly in Python (not by searching from value)?

Sorry for this basic question but my searches on this are not turning up anything other than how to get a dictionary's key based on its value which I would prefer not to use as I simply want the text/name of the key and am worried that searching by value may end up returning 2 or more keys if the dictionary has a lot of entries... what I am trying to do is this:
mydictionary={'keyname':'somevalue'}
for current in mydictionary:
result = mydictionary.(some_function_to_get_key_name)[current]
print result
"keyname"
The reason for this is that I am printing these out to a document and I want to use the key name and the value in doing this
I have seen the method below but this seems to just return the key's value
get(key[, default])
You should iterate over keys with:
for key in mydictionary:
print "key: %s , value: %s" % (key, mydictionary[key])
If you want to access both the key and value, use the following:
Python 2:
for key, value in my_dict.iteritems():
print(key, value)
Python 3:
for key, value in my_dict.items():
print(key, value)
The reason for this is that I am printing these out to a document and I want to use the key name and the value in doing this
Based on the above requirement this is what I would suggest:
keys = mydictionary.keys()
keys.sort()
for each in keys:
print "%s: %s" % (each, mydictionary.get(each))
If the dictionary contains one pair like this:
d = {'age':24}
then you can get as
field, value = d.items()[0]
For Python 3.5, do this:
key = list(d.keys())[0]
keys=[i for i in mydictionary.keys()] or
keys = list(mydictionary.keys())
As simple as that:
mydictionary={'keyname':'somevalue'}
result = mydictionary.popitem()[0]
You will modify your dictionary and should make a copy of it first
You could simply use * which unpacks the dictionary keys. Example:
d = {'x': 1, 'y': 2}
t = (*d,)
print(t) # ('x', 'y')
Iterate over dictionary (i) will return the key, then using it (i) to get the value
for i in D:
print "key: %s, value: %s" % (i, D[i])
For python 3
If you want to get only the keys use this. Replace print(key) with print(values) if you want the values.
for key,value in my_dict:
print(key)
What I sometimes do is I create another dictionary just to be able whatever I feel I need to access as string. Then I iterate over multiple dictionaries matching keys to build e.g. a table with first column as description.
dict_names = {'key1': 'Text 1', 'key2': 'Text 2'}
dict_values = {'key1': 0, 'key2': 1}
for key, value in dict_names.items():
print('{0} {1}'.format(dict_names[key], dict_values[key])
You can easily do for a huge amount of dictionaries to match data (I like the fact that with dictionary you can always refer to something well known as the key name)
yes I use dictionaries to store results of functions so I don't need to run these functions everytime I call them just only once and then access the results anytime.
EDIT: in my example the key name does not really matter (I personally like using the same key names as it is easier to go pick a single value from any of my matching dictionaries), just make sure the number of keys in each dictionary is the same
You can do this by casting the dict keys and values to list. It can also be be done for items.
Example:
f = {'one': 'police', 'two': 'oranges', 'three': 'car'}
list(f.keys())[0] = 'one'
list(f.keys())[1] = 'two'
list(f.values())[0] = 'police'
list(f.values())[1] = 'oranges'
if you just need to get a key-value from a simple dictionary like e.g:
os_type = {'ubuntu': '20.04'}
use popitem() method:
os, version = os_type.popitem()
print(os) # 'ubuntu'
print(version) # '20.04'
names=[key for key, value in mydictionary.items()]
if you have a dict like
d = {'age':24}
then you can get key and value by d.popitem()
key, value = d.popitem()
easily change the position of your keys and values,then use values to get key,
in dictionary keys can have same value but they(keys) should be different.
for instance if you have a list and the first value of it is a key for your problem and other values are the specs of the first value:
list1=["Name",'ID=13736','Phone:1313','Dep:pyhton']
you can save and use the data easily in Dictionary by this loop:
data_dict={}
for i in range(1, len(list1)):
data_dict[list1[i]]=list1[0]
print(data_dict)
{'ID=13736': 'Name', 'Phone:1313': 'Name', 'Dep:pyhton': 'Name'}
then you can find the key(name) base on any input value.

Categories

Resources