Formatting dictionary entries - python

I'm running python 2.7 in PS on a w10. I want to print the key and the value of a dictionary with every pair enumerated.
I do the following:
my_dict = {'key_one': 1, 'key_two': 2, 'key_three': 3}
for k, v in enumerate(my_dict.iteritems(), start = 1):
print k, v
which in turn gives:
1 ('key_one', 1)
2 ('key_two', 2)
3 ('key_three', 3)
How do I return the entries without the braces?
Example - I want to put a = sign in between my key-value pairs.

If you want to keep the indicies (from enumerate), then you're going to have to unpack the key and value from the dict items separates. Right now what you're calling k is actually an index, and what you're calling v is actually a key-value pair. Try something like this:
for i, (k, v) in enumerate(my_dict.iteritems(), start=1):
print i, k, v
That results in something like:
1 key_two 2
2 key_one 1
3 key_three 3
To get them formatted with an equals sign, you'd have to change the print statement to print i, "{}={}".format(k, v), which would result in something like:
1 key_two=2
2 key_one=1
3 key_three=3
If you need to retrieve the keys in a consistent order, use sorted(), like this:
for i, (k, v) in enumerate(sorted(my_dict.iteritems()), start=1):
...
Or, if you want to sort by values first instead of the keys first, you could specify a key function for the sorted() call. That would look like: sorted(my_dict.iteritems(), key=lambda (x, y): (y, x)). That would give you an output of
1 key_one=1
2 key_two=2
3 key_three=3

You don't need enumerate if you just want to print the existing key and values in your dictionary. Just use format():
for k, v in my_dict.items():
print '{} = {}'.format(k, v)
This would give:
key_one = 1
key_two = 2
key_three = 3

This works
my_dict = {'key_one': 1, 'key_two': 2, 'key_three': 3}
for key,value in my_dict.iteritems():
print key,value

Like this?
>>> for k, v in my_dict.iteritems():
... print k, v
...
key_two 2
key_one 1
key_three 3
or
>>> for i, (k, v) in enumerate(my_dict.iteritems(), start=1):
... print i, k, v
...
1 key_two 2
2 key_one 1
3 key_three 3

Simple one-line solution(for Python 2.7):
print '\n'.join([k+'='+ str(my_dict[k]) for k in my_dict.keys()])
The output:
key_two=2
key_one=1
key_three=3

You do not need enumerate() here. It is used when you need to iterate along with the index. you do not even need str.format() for achieving this. Simply place a entry of '=' string between your key, value and you will get what your desire. For example:
>>> my_dict = {'key_one': 1, 'key_two': 2, 'key_three': 3}
>>> for key, value in my_dict.items():
... print key, '=', value
...
key_two = 2
key_one = 1
key_three = 3
Edit: Based on the comment at user3030010's answer
Note: dict in python are un ordered. In case you want to maintain the order, use collections.OrderedDict() instead. It will preserve the order independent of the platform and python version. For example if you created the dict like:
>>> from collections import OrderedDict
>>> my_dict = OrderedDict()
>>> my_dict['key_one'] = 1
>>> my_dict['key_two'] = 2
>>> my_dict['key_three'] = 3
On iterating it, you will always get the same response as:
>>> for key, value in my_dict.items():
... print key, '=', value
...
key_one = 1
key_two = 2
key_three = 3

Related

Reversing the key values in a dictionary (advanced reverse string in Python)

So what I was trying to do was output the string "33k22k11k", which is just the last value followed by the reversed last key followed by the second last value followed by the second last reversed key and so on. I'm not sure how to get the reversed key value for the specific loop that I am in. From the code I currently I have, I get the output:
dict = {"k1":1, "k2":2, "k3":3}
current=""
current_k=""
for k,v in dict.items():
for i in k:
current_k=i+current_k
current=str(v)+current_k+current
print(current)
print(current_k)
33k2k1k22k1k11k
3k2k1k
Edited
First of all, if you are on python < 3.6, dict does not keep the order of items. You might want to use collections.OrderedDict for your purpose.
d = {"k1":1, "k2":2, "k3":3}
d.keys()
# dict_keys(['k2', 'k1', 'k3'])
whereas,
d = OrderedDict()
d['k1'] = 1
d['k2'] = 2
d['k3'] = 3
d.keys()
# odict_keys(['k1', 'k2', 'k3'])
With our new d, you can either add the key and values and reverse it:
res = ''
for k, v in d.items():
res += str(k) + str(v)
res[::-1]
# '33k22k11k'
or reversely iterate:
res = ''
for k, v in reversed(d.items()):
res += str(v)[::-1] + str(k)[::-1]
res
# '33k22k11k'
I may be wrong but it seems like you would want to reset the value of current_k each time you access a new key
dict = {"k1":1, "k2":2, "k3":3}
current=""
for k,v in dict.items():
current_k=""
for i in k:
current_k=i+current_k
current=str(v)+current_k+current
print(current)
print(current_k)
Why not simply do:
print(''.join([a+str(b) for a,b in dict.items()])[::-1])
Output:
"33k22k11k"
But if the values are different from the keys, do:
print(''.join([str(b)[::-1]+a for a,b in dict.items()[::-1]]))
You can use the Python map function to create the reversed string(using f-string) for each key/value pair and then join it.
dict1 = {"k1":1, "k2":2, "k3":3}
new_dict = "".join(map(lambda k, v: f'{k}{v}'[::-1] , dict1.keys(), dict1.values()))
Output:
33k22k11k
You can do something like this perhaps:
dict = {"k1":1, "k2":2, "k3":3}
print("".join(list(reversed([str(v)+"".join(reversed(k)) for k, v in dict.items()]))))
Output:
33k22k11k

Python Indexing

I have generated this following code first to calculate the frequencies of each element in the IDs list:
IDs =['fht142', 'fht142','fht178']
freqs = {}
for each in IDs:
freqs[each] = freqs.get(each, 0) + 1
print (each,freqs[each])
print (freqs)
so my freqs would look at this: {'fht178': 1, 'fht142': 2}
I just wonder how I could print out freqs as following:
fht178 1
fht142 2
many thx!!
data = {'fht178': 1, 'fht142': 2}
for k,v in data.iteritems():
print k,v
fht178 1
fht142 2
you can say:
for k, v in freqs.items():
print(k, v)

Python Compare Two Key/Value Pairs

Ive got two sets of key value pairs that look like this:
tom = {'coffee': 2, 'hotdog': 1}
and another like this:
namcat = {'hotdog stand':[hotdog, foodstand], 'cafe':[breakfast, coffee]}
Id like to compare whenever a key associated with 'tom' is the same as a value in 'namcat', and if so add 1 to a running total. I think its iterating over key-value pairs with lists that is causing me issues.
for k, v in namcat.items():
for item in v:
for key, value in tom.items():
if value == item:
running_total += 1
Demo:
>>> hotdog = 1
>>> coffee = 2
>>> foodstand = 6
>>> breakfast = 10
>>> tom = {'coffee': 2, 'hotdog': 1}
>>> namcat = {'hotdog stand':[hotdog, foodstand], 'cafe':[breakfast, coffee]}
>>> running_total = 0
>>> for k, v in namcat.items():
for item in v:
for key, value in tom.items():
if value == item:
running_total += 1
>>> running_total
2
This should do it. Hope it helps!

Dictionary help for Python

I have a dictionary, and I want to iterate over the keys, test the keys, and then print the keys that pass the test.
For example, my code looks like this at the moment:
x = {4:"a", 1:"b", 0:"c", 9:"d"}
for t in x:
if t > 2:
print t
However, all the output is, is just the key.
How do I get the code to print out the value at the end of the code, instead of the key?
Also, how do I get this in the form of a dictionary, {key : value}?
You could try this: print t, x[t]
Or this:
for key, val in x.items():
if key > 2:
print key, val
If you want to get only the pairs that you're printing into a new dictionary, then you have to put them there:
newdict = {}
for key, val in x.items():
if key > 2:
print key, val
# put all the keys > 2 into the new dict
newdict[key] = val
Of course that solution is printing when it inserts. If you're doing more than just a little script you will get more utility out of breaking functionality out, making sure that any given function does one, and only one, thing:
def filter_dict(x):
newdict = {}
for key, val in x.items():
if key > 2:
# put all the keys > 2 into the new dict
newdict[key] = val
def pretty_print(dct):
for k, v in dct.items():
print k, v
filtered = filter_dict(x)
pretty_print(dct)
This doesn't apply if you're just debugging, of course, and there are ways in which it depends on how large of a program you're writing: if you're doing a simple enough thing then the extra flexibility you get by breaking functionality up is lost because of the extra effort of figuring out exactly what any given thing does. That said: you should generally do it.
Additionally, the most idiomatic way to filter lists on a simple comparison in Python is to use a dict comprehension (new in Python 2.7/3.0):
filtered = {key: val for key, val in x if key > 2}
print [(k,v) for k,v in yourDict.items() if test(k)]
(You could just do k for k,v in... or v for k,v in.... If you only need values, you can use yourDict.values().)
x = {4:"a", 1:"b", 0:"c", 9:"d"}
for t in x:
if t > 2:
print '{}: {}'.format(t, x[t])
Slightly more pythonic:
>>> for key, value in x.iteritems():
... if key > 2:
... print '{}: {}'.format(key, value)
...
4: a
9: d
edit: To just print the value:
>>> for key, value in x.iteritems():
... if key > 2:
... print value
...
a
d
key as well as value:
x = {4:"a", 1:"b", 0:"c", 9:"d"}
for k,v in x.items():
if k>2: print"{%d : %s}"%(k,repr(v))
{4 : 'a'}
{9 : 'd'}
just value:
x = {4:"a", 1:"b", 0:"c", 9:"d"}
for k,v in x.items():
if k>2:print v
a
d
Just the keys:
>>> [k for k in x.iterkeys() if k > 2]
[4, 9]
Just the values:
>>> [v for k,v in x.iteritems() if k > 2]
['a', 'd']
Key-value pairs:
>>> [(k, v) for k,v in x.iteritems() if k > 2]
[(4, 'a'), (9, 'd')]
As a dict:
>>> dict((k,v) for k,v in x.iteritems() if k > 2)
{9: 'd', 4: 'a'}
If you want to create a dictionary with subset of items, you can also use a dictionary comprehension for Python 2.7+:
>>> x = {4:"a", 1:"b", 0:"c", 9:"d"}
>>> y = {k:v for k, v in x.iteritems() if k > 2}
>>> y
{9: 'd', 4: 'a'}
This is only a newer equivalent with only minor syntax differences for what Johnysweb shows in his answer:
>>> y = dict((k, v) for k, v in x.iteritems() if k > 2)
>>> y
{9: 'd', 4: 'a'}
The following list comprehension will print the key and value if key > 2.
Try this:
print [(key, value) for key, value in x.iteritems() if key > 2]
This solution prints the key t and the value in the dictionary x at key t.
x = {4:"a", 1:"b", 0:"c", 9:"d"}
for t in x:
if t > 2:
print t, x[t]
Using lambda function
(lambda x:[(k,v) for k,v in x.iteritems() if k > 2])(x)

dictionary values in python adding values

So here is my problem, i have a dictionary with following key => values:
6bc51fb21fd9eefef4ec97a241733cd59b71e8e14ad70e9068d32002:политичка -> 2
6bc51fb21fd9eefef4ec97a241733cd59b71e8e14ad70e9068d32002:државата -> 2
6bc51fb21fd9eefef4ec97a241733cd59b71e8e14ad70e9068d32002:енергично -> 1
1caa60ebf9459d9cd406f1a03e1719b675dcfaad78292edc7e4a56be:полициска -> 1
I have this code to show the keys needed:
for key, value in count_db.iteritems():
print key[:56]
So now i have:
6bc51fb21fd9eefef4ec97a241733cd59b71e8e14ad70e9068d32002 -> 2
6bc51fb21fd9eefef4ec97a241733cd59b71e8e14ad70e9068d32002 -> 2
6bc51fb21fd9eefef4ec97a241733cd59b71e8e14ad70e9068d32002 -> 1
1caa60ebf9459d9cd406f1a03e1719b675dcfaad78292edc7e4a56be -> 1
I need to merge them into:
6bc51fb21fd9eefef4ec97a241733cd59b71e8e14ad70e9068d32002 -> 5
1caa60ebf9459d9cd406f1a03e1719b675dcfaad78292edc7e4a56be -> 1
I have made this but i have not succeed in doing it correctly:
length_dic=len(count_db.keys())
for key, value in count_db.iteritems():
count_element=key[:56]
#print "%s => %s" % (key[:56], value) #value[:56]
for i in range(length_dic):
i+=1
if count_element == key[:56]:
itr+=int(value)
print i
length_dic=length_dic-1
Any hints?
A trivial approach would be:
result = {}
for key, value in count_db.iteritems():
result[key[:56]] = result.get(key[:56], 0) + value
You could also achieve the same with reduce if you want to get it on one line:
import collections
result = reduce(lambda x,y: x[y[0][:56]] += y[1] , count_db.iteritems(), collections.defaultdict(int))
Given your dictionary as
>>> spam={"6bc51fb21fd9eefef4ec97a241733cd59b71e8e14ad70e9068d32002:AAAA": 2,
"6bc51fb21fd9eefef4ec97a241733cd59b71e8e14ad70e9068d32002:BBBB": 2,
"6bc51fb21fd9eefef4ec97a241733cd59b71e8e14ad70e9068d32002:CCCC": 1,
"1caa60ebf9459d9cd406f1a03e1719b675dcfaad78292edc7e4a56be:DDDD": 1
}
you can somewhat do like the following
>>> bacon=collections.defaultdict(int)
>>> for k,v in [(k[:56],v) for k,v in spam.iteritems()]:
bacon[k]+=v
>>> bacon
defaultdict(<type 'int'>, {'6bc51fb21fd9eefef4ec97a241733cd59b71e8e14ad70e9068d32002': 5, '1caa60ebf9459d9cd406f1a03e1719b675dcfaad78292edc7e4a56be': 1})
>>>
This is exactly what the Counter object (in version 2.7+) is for:
import collections
c = collections.Counter()
for key, value in count_db.iteritems():
c[key[:56]] += value
I didn't understand why you did all that in your code. I think this would do the job:
tmp_dict = {}
for key, value in count_db.iteritems():
count_element=key[:56]
if count_element in tmp_dict:
tmp_dict[count_element] += value
else:
tmp_dict[count_element] = value

Categories

Resources