dict with one key and multiple values - python

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)

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

How to get the key element based on matching the key element in a dictionary?

I have a dictionary which looks like this:
dictionary={
"ABC-6m-RF-200605-1352": "s3://blabla1.com",
"ABC-3m-RF-200605-1352": "s3://blabla2.com",
"DEF-6m-RF-200605-1352": "s3://blabla3.com"
}
Now, I want to do a matching which takes input such as helper="ABC-6m" and tries to match this string to the key of the dictionary and returns the key (not the value)!
My code currently looks like this but it is not robust, i.e. sometimes it works and sometimes it does not:
dictionary_scan = dict((el, el[:7]) for el in dictionary)
#swapping key and value
dictionary_scan = dict((v, k) for k, v in dictionary.items())
#concat string components in helper variable
helper = 'ABC'+'-'+'6m'
out=list(value for key, value in dictionary_scan.items() if helper in key)
The expected output is: 'ABC-6m-RF-200605-1352'. Sometimes this works in my code but sometimes it does not. Is there a better and more robust way to do this?
If you make a dictionary that maps prefixes to full keys, you'll only be able to get one key with a given prefix.
If there can be multiple keys that start with helper, you need to check them all with an ordinary list comprehension.
out = [key for key in dictionary if key.startswith(helper)]

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

How to add to python dictionary without replacing

the current code I have is category1[name]=(number) however if the same name comes up the value in the dictionary is replaced by the new number how would I make it so instead of the value being replaced the original value is kept and the new value is also added, giving the key two values now, thanks.
You would have to make the dictionary point to lists instead of numbers, for example if you had two numbers for category cat1:
categories["cat1"] = [21, 78]
To make sure you add the new numbers to the list rather than replacing them, check it's in there first before adding it:
cat_val = # Some value
if cat_key in categories:
categories[cat_key].append(cat_val)
else:
# Initialise it to a list containing one item
categories[cat_key] = [cat_val]
To access the values, you simply use categories[cat_key] which would return [12] if there was one key with the value 12, and [12, 95] if there were two values for that key.
Note that if you don't want to store duplicate keys you can use a set rather than a list:
cat_val = # Some value
if cat_key in categories:
categories[cat_key].add(cat_val)
else:
# Initialise it to a set containing one item
categories[cat_key] = set(cat_val)
a key only has one value, you would need to make the value a tuple or list etc
If you know you are going to have multiple values for a key then i suggest you make the values capable of handling this when they are created
It's a little hard to understand your question.
I think you want this:
>>> d[key] = [4]
>>> d[key].append(5)
>>> d[key]
[4, 5]
Depending on what you expect, you could check if name - a key in your dictionary - already exists. If so, you might be able to change its current value to a list, containing both the previous and the new value.
I didn't test this, but maybe you want something like this:
mydict = {'key_1' : 'value_1', 'key_2' : 'value_2'}
another_key = 'key_2'
another_value = 'value_3'
if another_key in mydict.keys():
# another_key does already exist in mydict
mydict[another_key] = [mydict[another_key], another_value]
else:
# another_key doesn't exist in mydict
mydict[another_key] = another_value
Be careful when doing this more than one time! If it could happen that you want to store more than two values, you might want to add another check - to see if mydict[another_key] already is a list. If so, use .append() to add the third, fourth, ... value to it.
Otherwise you would get a collection of nested lists.
You can create a dictionary in which you map a key to a list of values, in which you would want to append a new value to the lists of values stored at each key.
d = dict([])
d["name"] = 1
x = d["name"]
d["name"] = [1] + x
I guess this is the easiest way:
category1 = {}
category1['firstKey'] = [7]
category1['firstKey'] += [9]
category1['firstKey']
should give you:
[7, 9]
So, just use lists of numbers instead of numbers.

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.

Categories

Resources