I have the a dictionary within a list
[{'123': 'some text'}]
I want my output to be a string with the keys and values separated like so
'123', 'some text'
Any suggestions?
Try this:
my_list_dict = [{'123': 'some text'}]
for elem in my_list_dict:
for key in elem:
print('key:', key)
print('value:', elem[key])
I think you want the values into the list, right?
Here is my aprouch
list_dict = [{'123': 'some text'}]
list_without_dict = []
for dict in list_dict:
for key in dict:
list_without_dict.append(key)
list_without_dict.append(dict[key])
print(list_without_dict)
simply iterate over the whole of your input keeping the keys and values and use ', '.join() to join a list into a string with ", " as a delimiter
wierd_input = [{'123': 'some text', 'foo':'boo'}, {'and':'another'}]
all_parts = []
for dictionary in wierd_input:
for key, value in dictionary.items():
all_parts.extend((key, value))
print(", ".join(all_parts))
>>123, some text, foo, boo, and, another
you can convert this into a generator if you want to join such objects frequently in your code
def iterate_over_wierd(wierd):
for dictionary in wierd:
for key, value in dictionary.items():
yield key
yield value
print(", ".join(iterate_over_wierd(wierd_input)))
if you desperately need a one-liner you can use itertools
import itertools
', '.join(itertools.chain.from_iterable(itertools.chain.from_iterable(map(dict.items,wierd_input))))
but I advise against this as the one liner is very confusing and hacky, better stick to the former two
Related
I was learning Python and came upon a problem: To convert a list of list to dictionary based on a certain key.
If the input is: [['key1','h1'],['key2','h2'],['key3','h3'],['key1','h4'],['key1','h5'], ['key2','h6']]
The output is: {'key1':{'h1','h4','h5'}, 'key2':{'h2', 'h6'}, 'key3':{'h3'}}
The logic being, the first element of the inner array is considered as the key for the new dictionary.
I am currently doing it the dirty way by iterating over the entire list. But, is there a better way to do it?
You'll have to iterate over the list. One way is to use dict.setdefault:
out = {}
for k,v in lst:
out.setdefault(k, set()).add(v)
This is the same as the following conditional loop:
out = {}
for k,v in lst:
if k in out:
out[k].add(v)
else:
out[k] = {v}
Output:
{'key1': {'h1', 'h4', 'h5'}, 'key2': {'h2', 'h6'}, 'key3': {'h3'}}
Maybe it is ordinary issue regarding iterating thru a dict. Please find below imovel.txt file, whose content is as follows:
{'Andar': ['primeiro', 'segundo', 'terceiro'], 'Apto': ['101','201','301']}
As you can see this is not a ordinary dictionary, with a key value pair; but a key with a list as key and another list as value
My code is:
#/usr/bin/python
def load_dict_from_file():
f = open('../txt/imovel.txt','r')
data=f.read()
f.close()
return eval(data)
thisdict = load_dict_from_file()
for key,value in thisdict.items():
print(value)
and yields :
['primeiro', 'segundo', 'terceiro'] ['101', '201', '301']
I would like to print a key,value pair like
{'primeiro':'101, 'segundo':'201', 'terceiro':'301'}
Given such txt file above, is it possible?
You should use the builtin json module to parse but either way, you'll still have the same structure.
There are a few things you can do.
If you know both of the base key names('Andar' and 'Apto') you can do it as a one line dict comprehension by zipping the values together.
# what you'll get from the file
thisdict = {'Andar': ['primeiro', 'segundo', 'terceiro'], 'Apto': ['101','201','301']}
# One line dict comprehension
newdict = {key: value for key, value in zip(thisdict['Andar'], thisdict['Apto'])}
print(newdict)
If you don't know the names of the keys, you could call next on an iterator assuming they're the first 2 lists in your structure.
# what you'll get from the file
thisdict = {'Andar': ['primeiro', 'segundo', 'terceiro'], 'Apto': ['101','201','301']}
# create an iterator of the values since the keys are meaningless here
iterator = iter(thisdict.values())
# the first group of values are the keys
keys = next(iterator, None)
# and the second are the values
values = next(iterator, None)
# zip them together and have dict do the work for you
newdict = dict(zip(keys, values))
print(newdict)
As other folks have noted, that looks like JSON, and it'd probably be easier to parse it read through it as such. But if that's not an option for some reason, you can look through your dictionary this way if all of your lists at each key are the same length:
for i, res in enumerate(dict[list(dict)[0]]):
ith_values = [elem[i] for elem in dict.values()]
print(ith_values)
If they're all different lengths, then you'll need to put some logic to check for that and print a blank or do some error handling for looking past the end of the list.
My dict (cpc_docs) has a structure like
{
sym1:[app1, app2, app3],
sym2:[app1, app6, app56, app89],
sym3:[app3, app887]
}
My dict has 15K keys and they are unique strings. Values for each key are a list of app numbers and they can appear as values for more than one key.
I've looked here [Python: Best Way to Exchange Keys with Values in a Dictionary?, but since my value is a list, i get an error unhashable type: list
I've tried the following methods:
res = dict((v,k) for k,v in cpc_docs.items())
for x,y in cpc_docs.items():
res.setdefault(y,[]).append(x)
new_dict = dict (zip(cpc_docs.values(),cpc_docs.keys()))
None of these work of course since my values are lists.
I want each unique element from the value lists and all of its keys as a list.
Something like this:
{
app1:[sym1, sym2]
app2:[sym1]
app3:[sym1, sym3]
app6:[sym2]
app56:[sym2]
app89:[sym2]
app887:[sym3]
}
A bonus would be to order the new dict based on the len of each value list. So like:
{
app1:[sym1, sym2]
app3:[sym1, sym3]
app2:[sym1]
app6:[sym2]
app56:[sym2]
app89:[sym2]
app887:[sym3]
}
Your setdefault code is almost there, you just need an extra loop over the lists of values:
res = {}
for k, lst in cpc_docs.items():
for v in lst:
res.setdefault(v, []).append(k)
First create a list of key, value tuples
new_list=[]
for k,v in cpc_docs.items():
for i in range(len(v)):
new_list.append((k,v[i]))
Then for each tuple in the list, add the key if it isn't in the dict and append the
doc_cpc = defaultdict(set)
for tup in cpc_doc_list:
doc_cpc[tup[1]].add(tup[0])
Probably many better ways, but this works.
I have the following:
list_of_values = []
x = { 'key1': 1, 'key2': 2, 'key3': 3 }
How can I iterate through the dictionary and append one of those values into that list? What if I only want to append the value of 'key2'.
If you only want to append a specific set of values you don't need to iterate through the dictionary can simply add it to the list
list_of_values.append(x["key2"])
However, if you insist on iterating through the dictionary you can iterate through the key value pairs:
for key, value in x.items():
if key == "key2":
list_of_values.append(value)
If you really want to iterate over the dictionary I would suggest using list comprehensions and thereby creating a new list and inserting 'key2' :
list_of_values = [x[key] for key in x if key == 'key2']
because that can be easily extended to search for multiple keywords:
keys_to_add = ['key2'] # Add the other keys to that list.
list_of_values = [x[key] for key in x if key in keys_to_add]
That has the simple advantage that you create your result in one step and don't need to append multiple times. After you are finished iterating over the dictionary you can append the list, just to make it interesting, you can do it without append by just adding the new list to the older one:
list_of_values += [x[key] for key in x if key in keys_to_add]
Notice how I add them in-place with += which is exactly equivalent to calling list_of_values.append(...).
list_of_values = []
x = { 'key1': 1, 'key2': 2, 'key3': 3 }
list_of_values.append(x['key2'])
I have a dictionary with values attached. I am able to get all keys. I have done searching around and a lot of people are saying to put the keys in a list, However I need the values attached to that key and the values must stay the same.
mydict = {'Car':'BMW','Speed':'kph','Range':33}
for keys in mydict:
print(keys)
What I am after is any two of the keys and their values to be printed out.
I don't fully understand what are you looking for.
You want to print values also? Go for
mydict = {'Car':'BMW','Speed':'kph','Range':33}
for keys in mydict:
print(keys,":",mydict[keys])
You want just print 2 of them?
mydict = {'Car':'BMW','Speed':'kph','Range':33}
from itertools import islice
def take(n, iterable):
return list(islice(iterable, n))
n_items = take(2, mydict.iteritems())
print(n_items)
You'll need itertools from pip tho.
Well, even if you put them in a list, you can still get the values:
mydict = {'Car':'BMW','Speed':'kph','Range':33}
keys = list(mydict)
for key in keys:
print(mydict[keys])
If you want only two keys you can do:
keys = keys[:2]
And if you want a new dictionary using only those two keys:
mynewdict = {k:v for k,v in mydict.items() if k in keys}
And probably the shortest:
for key in list(mydict)[:2]:
print(key, mydict[key])